Open In App

Python – Add Values to Dictionary of List

Last Updated : 01 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • We access the list directly using the key (a[‘x’]).
  • append() method adds the new value (30) to the end of the list.
  • This is simple and efficient but assumes the key already exists in the dictionary.

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

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)  

Output
{'y': [5]}

Explanation:

  • setdefault() checks if the key exists in the dictionary.
  • If the key is absent, it initializes it with the provided default value ([] in this case).
  • The value is then appended to the list.

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:

  • A defaultdict() automatically initializes a new list when a missing key is accessed.
  • This eliminates the need for manual checks or initialization.

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:

  • We iterate through all key-value pairs in the dictionary using data.items().
  • For each pair, we concatenate the new value ([4]) to the existing list (v).
  • The updated dictionary is reassigned to data.


Next Article

Similar Reads