How to avoid overwrite for dictionary append?

China☆狼群 提交于 2020-02-08 04:32:36

问题


For example, I have:

dic={'a': 1, 'b': 2, 'c': 3}

Now I'd like another 'c':4 add into dictionary. It'll overwrite the existing 'c':3.

How could I get dic like:

dic={'a': 1, 'b': 2, 'c': 3, 'c':4}

回答1:


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]})



回答2:


You can't have duplicate keys within a single dictionary -- what behavior would you expect when you tried to look something up? However, you can associate a list with the key in order to store multiple objects. This small change in your dictionary's structure would allow for {'c' : [3, 4]}, which ultimately accomplishes the behavior you're looking for.



来源:https://stackoverflow.com/questions/42846956/how-to-avoid-overwrite-for-dictionary-append

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!