Open In App

Python – Update values of a list of dictionaries

Last Updated : 27 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.



Next Article

Similar Reads