Praful Bagai
Praful Bagai

Reputation: 17412

How to add multiple values to a dictionary key?

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

Upvotes: 109

Views: 610015

Answers (3)

cottontail
cottontail

Reputation: 23449

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

Upvotes: 4

President James K. Polk
President James K. Polk

Reputation: 42018

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.

Upvotes: 190

MattDMo
MattDMo

Reputation: 102922

How about

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

This will result in:

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

Is that what you were looking for?

Upvotes: 28

Related Questions