为什么我的一些字典键和值消失了?



这是我的代码:

listy = [[(100, 1), (90, 2), (90, 2), (80, 3), (70, 4)], [(100, 1), (90, 2), (90, 2), (80, 3), (80, 3)]]
track = [dict(x) for x in listy] 
print(track)

我有一个嵌套的元组列表,我正在将它们转换为列表中的字典,但问题是从元组更改后某些键和值消失了。输出是这样的:

[{100: 1, 90: 2, 80: 3, 70: 4}, {100: 1, 90: 2, 80: 3}]

相反,输出应该是这样的:

[{100:1, 90:2, 90:2, 80:3, 70:4},{100:1, 90:2, 90:2, 80:3, 80:3}]

为什么我的代码给出错误的输出,以及问题的可能解决方案是什么。我正在使用Python 3.x

Python 不允许字典中使用重复键。在类似于您的示例的内容中:

>>> d={100:1, 90:2, 90:3, 80:3, 70:4}
>>> d[90]
3

如果它允许重复键,则无法知道是返回2还是390

如果要跟踪元组的计数,可以使用collections.Counter

from collections import Counter
listy = [[(100, 1), (90, 2), (90, 2), (80, 3), (70, 4)], [(100, 1), (90, 2), (90, 2), (80, 3), (80, 3)]]
count = [Counter(x) for x in listy]
print(count)

这给出了输出:

[Counter({(90, 2): 2, (100, 1): 1, (80, 3): 1, (70, 4): 1}), Counter({(90, 2): 2, (80, 3): 2, (100, 1): 1})]

或者,如果您只想将键与值相关联,则可以使用defaultdict

from collections import defaultdict
listy = [
[(100, 1), (90, 2), (90, 2), (80, 3), (70, 4)],
[(100, 1), (90, 2), (90, 2), (80, 3), (80, 3)],
]

update_lists = []
for l in listy:
# if a key is not found, automatically create a list
u = defaultdict(list)
for (k, v) in l:
u[k].append(v)
update_lists.append(u)
print(update_lists)

这给出了以下输出:

[defaultdict(<class 'list'>, {100: [1], 90: [2, 2], 80: [3], 70: [4]}), defaultdict(<class 'list'>, {100: [1], 90: [2, 2], 80: [3, 3]})]

值似乎消失了,因为您尝试使用重复键创建字典:

data = [(1, 'one'), (1, 'two'), (2, 'three')]
dictionary = dict(data)

将导致:

{1: 'one', 2: 'three'}

Python 字典不支持重复键。

@Mahir 您可以将多个值关联到字典中的单个键,如下所示

multi_value_dict = {}
multi_value_dict.setdefault(key, []).append(value)

最新更新