python - 如果键多次出现而不导入,如何更新python字典中的值?
问题描述
假设我有一个包含多次出现相同键的元组列表。我想将它们转换成字典,但我不希望键重复或覆盖以前的键。我想在不导入包的情况下做到这一点。
[("John", 14), ("Bob", 5), ("John", 21)]
turn it into:
{"John": [14, 21],
"Bob": [5]}
解决方案
from collections import defaultdict
yourlist = [("John", 14), ("Bob", 5), ("John", 21)]
d = defaultdict(list)
for k, v in yourlist:
d[k].append(v)
print(d)
输出:
defaultdict(<class 'list'>, {'John': [14, 21], 'Bob': [5]})
要使其成为真正的dict
ionary,请添加以下行:
d = dict(d)
然后:
print(d)
会给:
{'John': [14, 21], 'Bob': [5]}
编辑:
正如评论中提到的OP,他不想使用任何进口。所以试试:
yourlist = [("John", 14), ("Bob", 5), ("John", 21)]
d = {}
for x, y in yourlist:
if x in d:
d[x].append(y)
else:
d[x] = [y]
print(d)
输出:
{'John': [14, 21], 'Bob': [5]}