104

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

cottontail
  • 10,268
  • 18
  • 50
  • 51
Praful Bagai
  • 16,684
  • 50
  • 136
  • 267

3 Answers3

183

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. Now, noting that setdefault returns the value, 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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
26

How about

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

This will result in:

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

Is that what you were looking for?

MattDMo
  • 100,794
  • 21
  • 241
  • 231
2
  • Append list elements

If the dict values need to be extended by another list, extend() method of lists may be useful.

a = {}
a.setdefault('abc', []).append(1)       # {'abc': [1]}
a.setdefault('abc', []).extend([2, 3])  # a is now {'abc': [1, 2, 3]}

This can be especially useful in a loop where values need to be appended or extended depending on datatype.

a = {}
some_key = 'abc'
for v in [1, 2, 3, [2, 4]]:
    if isinstance(v, list):
        a.setdefault(some_key, []).extend(v)
    else:
        a.setdefault(some_key, []).append(v)
a
# {'abc': [1, 2, 3, 2, 4]}
  • Append list elements without duplicates

If there's a dictionary such as a = {'abc': [1, 2, 3]} and it needs to be extended by [2, 4] without duplicates, checking for duplicates (via in operator) should do the trick. The magic of get() method is that a default value can be set (in this case empty set ([])) in case a key doesn't exist in a, so that the membership test doesn't error out.

a = {some_key: [1, 2, 3]}

for v in [2, 4]:
    if v not in a.get(some_key, []):
        a.setdefault(some_key, []).append(v)
a
# {'abc': [1, 2, 3, 4]}
cottontail
  • 10,268
  • 18
  • 50
  • 51