如何避免覆盖字典追加? [英] How to avoid overwrite for dictionary append?
本文介绍了如何避免覆盖字典追加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有:
dic={'a': 1, 'b': 2, 'c': 3}
现在,我想再添加一个'c':4
到字典中.它将覆盖现有的'c':3
.
Now I'd like another 'c':4
add into dictionary. It'll overwrite the existing 'c':3
.
我怎么能得到dic
?
dic={'a': 1, 'b': 2, 'c': 3, 'c':4}
推荐答案
字典键必须是唯一的.但是您可以将列表作为值,这样就可以在其中存储多个值.可以通过使用collections.defaultdict
来实现,如下所示.
(示例是从IPython会话复制的.)
Dictionary keys must be unique. But you can have a list as a value so you can store multiple values in it. This can be accomplished by using collections.defaultdict
as shown below.
(Example copied from IPython session.)
In [1]: from collections import defaultdict
In [2]: d = defaultdict(list)
In [3]: d['a'].append(1)
In [4]: d['b'].append(2)
In [5]: d['c'].append(3)
In [6]: d['c'].append(4)
In [7]: d
Out[7]: defaultdict(list, {'a': [1], 'b': [2], 'c': [3, 4]})
这篇关于如何避免覆盖字典追加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文