How to add multiple values to a dictionary key?

Viewed 488086

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

3 Answers
  • 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]}
Related