元组列表转字典时如何保留所有含重复键的条目?
处理含重复键的元组列表转字典的问题
当你有如下元组列表:
points = [(1, 2), (1, 5), (2, 5), (3, 3), (3, 7), (6, 5), (9, 9)]
直接使用dict()转换为字典时:
dictionary = dict(points)
会得到丢失部分条目的结果:
{1: 5, 2: 5, 3: 7, 6: 5, 9: 9}
其中(1,2)和(3,3)这两个条目被移除了。
原因说明
这是因为Python字典不允许存在重复键,转换过程中后出现的同键值对会直接覆盖之前的条目。
解决方案
如果需要保留所有同键对应的数值,可以借助collections.defaultdict,将每个键对应的值存储为列表:
from collections import defaultdict result = defaultdict(list) for key, value in points: result[key].append(value)
转换后的字典结构为:
{1: [2,5], 2: [5], 3: [3,7], 6: [5], 9: [9]}
内容的提问来源于stack exchange,提问作者Stef Val
相关产品推荐
相关产品推荐

