Python – Update values of a list of dictionaries
Last Updated :
27 Jan, 2025
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 example, consider a list of dictionaries like a = [{‘name’: ‘sravan’, ‘subjects’: [‘java’, ‘python’]}, {‘name’: ‘bobby’, ‘subjects’: [‘c/cpp’, ‘java’]}, {‘name’: ‘gnanesh’, ‘subjects’: [‘html’, ‘sql’]}]. The goal is to update specific values in the subjects key based on a given mapping. For instance, replacing ‘python’ with ‘html’ or ‘php’ with ‘php-mysql’. Using an update dictionary and iterating over the list allows modification of the dictionaries in place. After applying the updates, the resulting list becomes: a = [{‘name’: ‘sravan’, ‘subjects’: [‘java’, ‘html’]}, {‘name’: ‘bobby’, ‘subjects’: [‘c/cpp’, ‘java’]},{‘name’: ‘gnanesh’, ‘subjects’: [‘html’, ‘sql’]}].
Using list comprehension
This method is highly efficient for updating values in-place and is considered both cleaner and faster. By using enumerate, we can iterate over the list along with its index, allowing us to update specific items in the list using conditions in a single pass. It’s a concise approach to modifying dictionary values.
Python
a = [
{'name': 'sravan', 'subjects': ['java', 'python']},
{'name': 'bobby', 'subjects': ['c/cpp', 'java']},
{'name': 'ojsawi', 'subjects': ['iot', 'cloud']},
{'name': 'rohith', 'subjects': ['php', 'os']},
{'name': 'gnanesh', 'subjects': ['html', 'sql']}
]
# update dictionary
b = {
0: ('python', 'html'),
2: ('java', 'dbms'),
3: ('php', 'php-mysql')
}
for idx, (old_sub, new_sub) in b.items():
a[idx]['subjects'] = [new_sub if sub == old_sub else sub for sub in a[idx]['subjects']]
print(a)
Output
[{'name': 'sravan', 'subjects': ['java', 'html']},
{'name': 'bobby', 'subjects': ['c/cpp', 'java']},
{'name': 'ojsawi', 'subjects': ['iot', 'cloud']},
{'name': 'rohith', 'subjects': ['php-mysql', 'os']},
{'name': 'gnanesh', 'subjects': ['html', 'sql']}]
Explanation: This code iterates through the b.items() update dictionary and for each index idx, it uses a list comprehension to check each subject in a[idx][‘subjects’]. If a subject matches old_sub, it is replaced with new_sub.
Using map
map() combined with a lambda expression offers a more functional programming approach. It applies a given function to each element of the list. This method is clean and can be especially useful when we need to apply transformations based on conditions, such as updating values in a list of dictionaries.
Python
a = [
{'name': 'sravan', 'subjects': ['java', 'python']},
{'name': 'bobby', 'subjects': ['c/cpp', 'java']},
{'name': 'ojsawi', 'subjects': ['iot', 'cloud']},
{'name': 'rohith', 'subjects': ['php', 'os']},
{'name': 'gnanesh', 'subjects': ['html', 'sql']}
]
# update dictionary
b = {
0: ('python', 'html'),
2: ('java', 'dbms'),
3: ('php', 'php-mysql')
}
for idx, (old_sub, new_sub) in b.items():
a[idx]['subjects'] = list(map(lambda sub: new_sub if sub == old_sub else sub, a[idx]['subjects']))
print(a)
Output
[{'name': 'sravan', 'subjects': ['java', 'html']},
{'name': 'bobby', 'subjects': ['c/cpp', 'java']},
{'name': 'ojsawi', 'subjects': ['iot', 'cloud']},
{'name': 'rohith', 'subjects': ['php-mysql', 'os']},
{'name': 'gnanesh', 'subjects': ['html', 'sql']}]
Explanation: This code iterates through the b.items() update dictionary, and for each index idx, it applies a lambda function to check the subjects in a[idx][‘subjects’]. If a subject matches old_sub, it is replaced with new_sub using map().
Using loop
This traditional approach involves a simple for loop, which allows us to manually iterate over the elements and perform updates. Although this method might require more code, it is straightforward and easy to understand. It’s a good option when we want more control over the iteration process and need to perform more complex operations.
Python
a = [
{'name': 'sravan', 'subjects': ['java', 'python']},
{'name': 'bobby', 'subjects': ['c/cpp', 'java']},
{'name': 'ojsawi', 'subjects': ['iot', 'cloud']},
{'name': 'rohith', 'subjects': ['php', 'os']},
{'name': 'gnanesh', 'subjects': ['html', 'sql']}
]
# update dictionary
b = {
0: ('python', 'html'),
2: ('java', 'dbms'),
3: ('php', 'php-mysql')
}
for idx, (old_sub, new_sub) in b.items():
for i, subject in enumerate(a[idx]['subjects']):
if subject == old_sub:
a[idx]['subjects'][i] = new_sub
print(a)
Output
[{'name': 'sravan', 'subjects': ['java', 'html']},
{'name': 'bobby', 'subjects': ['c/cpp', 'java']},
{'name': 'ojsawi', 'subjects': ['iot', 'cloud']},
{'name': 'rohith', 'subjects': ['php-mysql', 'os']},
{'name': 'gnanesh', 'subjects': ['html', 'sql']}]
Explanation: This code iterates through the b.items() update dictionary and for each index idx, the inner loop checks the subjects in a[idx][‘subjects’]. If a subject matches old_sub, it is replaced with new_sub.
Similar Reads
Python - Add Values to Dictionary of List
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 efficien
3 min read
Sort a List of Python Dictionaries by a Value
Sorting a list of dictionaries by a specific value is a common task in Python programming. Whether you're dealing with data manipulation, analysis, or simply organizing information, having the ability to sort dictionaries based on a particular key is essential. In this article, we will explore diffe
3 min read
Updating Value List in Dictionary - Python
We are given a dictionary where the values are lists and our task is to update these lists, this can happen when adding new elements to the lists or modifying existing values in them. For example, if we have a dictionary with a list as a value like this: {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3} the
4 min read
Even Values Update in Dictionary - Python
The task of updating even values in a dictionary in Python involves modifying the values associated with specific keys based on a condition, typically checking whether the values are even. For example, consider a dictionary like d = {'gfg': 6, 'is': 4, 'best': 7}. The goal is to update the values by
3 min read
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 - Print dictionary of list values
In this article, we will explore various ways on How to Print Dictionary in Python of list values. A dictionary of list values means a dictionary contains values as a list of dictionaries in Python. Example: {'key1': [{'key1': value,......,'key n': value}........{'key1': value,......,'key n': value}
4 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 efficientl
2 min read
Python Update Dictionary Value by Key
A Dictionary in Python is an unordered collection of key-value pairs. Each key must be unique, and you can use various data types for both keys and values. Dictionaries are enclosed in curly braces {}, and the key-value pairs are separated by colons. Python dictionaries are mutable, meaning you can
3 min read
Python Filter List of Dictionaries Based on Key Value
Python, a versatile and powerful programming language, offers multiple ways to manipulate and process data. When working with a list of dictionaries, you may often need to filter the data based on specific key-value pairs. In this article, we will explore three different methods to achieve this task
3 min read
Inverse Dictionary Values List - Python
We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]} Using defau
2 min read