How to add multiple values to a dictionary key in python?

PythonEnthusiast picture PythonEnthusiast · Dec 14, 2013 · Viewed 379.8k times · Source

I want to add multiple values to a specific key in a python dictionary. How can I do that?

a = {}
a["abc"] = 1
a["abc"] = 2

This will replace the value of a["abc"] from 1 to 2.

What I want instead is for a["abc"] to have multiple values(both 1 and 2).

Answer

President James K. Polk picture President James K. Polk · Dec 14, 2013

Make the value a list, e.g.

a["abc"] = [1, 2, "bob"]

UPDATE:

There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.

key = "somekey"
a.setdefault(key, [])
a[key].append(1)

Results:

>>> a
{'somekey': [1]}

Next, try:

key = "somekey"
a.setdefault(key, [])
a[key].append(2)

Results:

>>> a
{'somekey': [1, 2]}

The magic of setdefault is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault returns the key you can combine these into a single line:

a.setdefault("somekey",[]).append("bob")

Results:

>>> a
{'somekey': [1, 2, 'bob']}

You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.