Python Add Values to Dictionary of List (original) (raw)

Last Updated : 01 Feb, 2025

A dictionary of lists allows storing grouped values under specific keys. For example, in a = {'x': [10, 20]}, the key 'x' maps to the list [10, 20]. To add values like 30 to this list, we use efficient methods to update the dictionary dynamically. Let’s look at some commonly used methods to efficiently add values to a dictionary of lists.

Using append()

If we are certain that the key exists in the dictionary, we can simply access the list associated with the key and use append() method.

Python `

Initialize a dictionary of lists

a = {'x': [10, 20]}

Append a value to the list under the key 'x'

a['x'].append(30)

print(a)

`

Output

{'x': [10, 20, 30]}

**Explanation:

Let's explore some more ways and see how we can add values to dictionary of list.

Table of Content

Using setdefault()

When there is a possibility that the key might not exist, we can use setdefault() method. This ensures the key exists and initializes it with an empty list if it doesn't.

Python `

Initialize an empty dictionary

a = {}

Ensure the key exists and append a value to the list

a.setdefault('y', []).append(5)

print(a)

`

**Explanation:

Using defaultdict() from collections

defaultdict() automatically initializes a default value for missing keys, making it a great option for handling dynamic updates.

Python `

from collections import defaultdict

Create a defaultdict with lists as the default value

a = defaultdict(list)

Append values to the list under the key 'z'

a['z'].append(100)
a['z'].append(200)

print(a)

`

Output

defaultdict(<class 'list'>, {'z': [100, 200]})

**Explanation:

Using Dictionary Comprehension

If we need to update multiple keys at once, dictionary comprehension is a concise and efficient option.

Python `

Initialize a dictionary with some lists

a = {'p': [1, 2], 'q': [3]}

Add a new value to each list

a = {k: v + [10] for k, v in a.items()}

print(a)

`

Output

{'p': [1, 2, 10], 'q': [3, 10]}

**Explanation: