Skip to content Skip to sidebar Skip to footer

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. It'll overwrite the existing 'c':3. How could I get dic like: dic={'a': 1, 'b':

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

Solution 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.


Post a Comment for "How To Avoid Overwrite For Dictionary Append?"