Python:从zip附加到字典 [英] Python: Append to dictionary from a zip
本文介绍了Python:从zip附加到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以说我有以下列表,例如[key,value, key,value, key,value]
我想把它变成字典,看起来像:
{key:value, key:value, key:value}
Lets say I have the following list such as [key,value, key,value, key,value]
and I want to turn it into a dictionary which looks like:
{key:value, key:value, key:value}
我尝试过
dict(zip(mydict[::2], mydict[1::2]))
但是,其中一个键的原始值一直被覆盖.如果键已经存在,如何更改它以便附加到字典中?
However, the original values for one of the keys keeps being overwritten. How can I change this so it appends to the dictionary if the key already exists?
推荐答案
我不确定我是否会误会.字典中不能有重复的键.一个将覆盖另一个.
I'm not sure if I'm misunderstanding then. You cannot have repeated keys inside a dictionary. One will overwrite the other.
[in] >>> d = dict([('x',3),('x',4)])
[in] >>> print(d)
[out] >>> {'x': 4}
也许您正在考虑使用defaultdict
Maybe you're thinking of a defaultdict
[in] >>> from collections import defaultdict
[in] >>> d = defaultdict(list)
[in] >>> for k,v in [('x',3),('x',4)]:
>>> d[k].append(v)
[in] >>> print(d)
[out] >>> defaultdict(<class 'list'>, {'x': [3, 4]})
这篇关于Python:从zip附加到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文