How to add multiple values to a dictionary key in python? [closed] How to add multiple values to a dictionary key in python? [closed] python python

How to add multiple values to a dictionary key in python? [closed]


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.


How about

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

This will result in:

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

Is that what you were looking for?