LookIntoEast
LookIntoEast

Reputation: 8798

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': 2, 'c': 3, 'c':4}

Upvotes: 0

Views: 4698

Answers (2)

Roland Smith
Roland Smith

Reputation: 43495

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

Upvotes: 5

Benjamin Engwall
Benjamin Engwall

Reputation: 294

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.

Upvotes: 0

Related Questions