python - 为每个键构建一个字典,一组来自元组列表的关联值

标签 python list dictionary set tuples

我有一个这样的元组列表:

list = [(1,2),(1,3),(1,5),(0,8),(0,9),(0,1),(3,6),(3,7)]

我想用这样的关联值集构建一个字典:

result = {1:{2,3,5},0:{8,9,1},3:{6,7}}

我有这个代码:

return {x:y for (x,y) in list}

result = {1: 5, 0: 1, 3: 7}

但我只有最后一个值,我想要一个集合中的所有关联值。

提前致谢

最佳答案

defaultdict 可以在不检查是否存在的情况下为键添加值

from collections import defaultdict
mylist = [(1,2),(1,3),(1,5),(0,8),(0,9),(0,1),(3,6),(3,7)]
result = defaultdict(list)
for item in mylist:
    result[item[0]].append(item[1])

关于python - 为每个键构建一个字典,一组来自元组列表的关联值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64534005/

相关文章:

python - 我碰巧发现了这段代码 :"With for w in words:, 该示例将尝试创建一个无限列表

html - 将 ul 嵌套在 ol 中

python - 使用 {tuple :float} format 来自 dict 的 x 和 y 标签在 python matplotlib 中创建热图

python - 使用 SortedDictionary for .net(从 C# .dll 导入)

python - 如何将多个 gpx 文件加载到 PostGIS 中?

python - 当 openssl s_client -connect 工作时,为什么 python 2.7 请求 ssl 失败?

python - 如何通过删除重复项和移动值从现有列表中创建新列表?

python - 隐藏 turtle 窗口?

python - 如何使用 pandas 确定每个唯一用户的优先操作

python - Python 字典中的数据太多?