Python - Add Values to Dictionary of List
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:
- 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)
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)
Outputdefaultdict(<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.
Similar Reads
Python Convert Dictionary to List of Values Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
3 min read
Python Dictionary Add Value to Existing Key The task of adding a value to an existing key in a Python dictionary involves modifying the value associated with a key that is already present. Unlike adding new key-value pairs, this operation focuses on updating the value of an existing key, allowing us to increment, concatenate or otherwise adju
2 min read
Get Python Dictionary Values as List - Python We are given a dictionary where the values are lists and our task is to retrieve all the values as a single flattened list. For example, given the dictionary: d = {"a": [1, 2], "b": [3, 4], "c": [5]} the expected output is: [1, 2, 3, 4, 5]Using itertools.chain()itertools.chain() function efficiently
2 min read
How to Add Values to Dictionary in Python The task of adding values to a dictionary in Python involves inserting new key-value pairs or modifying existing ones. A dictionary stores data in key-value pairs, where each key must be unique. Adding values allows us to expand or update the dictionary's contents, enabling dynamic manipulation of d
3 min read
Python - Update values of a list of dictionaries The task of updating the values of a list of dictionaries in Python involves modifying specific keys or values within each dictionary in the list based on given criteria or conditions. This task is commonly encountered when working with structured data that needs transformation or enrichment.For exa
4 min read