简体   繁体   English

如何避免覆盖字典追加?

[英]How to avoid overwrite for dictionary append?

For example, I have: 例如,我有:

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

Now I'd like another 'c':4 add into dictionary. 现在,我想再添加一个'c':4到字典中。 It'll overwrite the existing 'c':3 . 它将覆盖现有的'c':3

How could I get dic like: 我如何获得dic像:

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

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. 这可以通过使用collections.defaultdict来实现,如下所示。 (Example copied from IPython session.) (示例从IPython会话复制。)

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

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. 字典结构的微小变化将允许{'c' : [3, 4]} ,最终实现您要寻找的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM