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 Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read