![]() |
VOOZH | about |
The task of adding custom values as keys in a list of dictionaries involves inserting a new key-value pair into each dictionary within the list. In Python, dictionaries are mutable, meaning the key-value pairs can be modified or added easily. When working with a list of dictionaries, the goal is to append a new key to each dictionary in the list with a corresponding value.
For example, given a list of dictionaries a = [{'Gfg': 6, 'is': 9, 'best': 10}, {'Gfg': 8, 'is': 11, 'best': 19}] and a new key k = 'CS' with corresponding values from the list b = [6, 7], we can iterate over the list and add the new key-value pair to each dictionary. After this operation, each dictionary in the list will have a new key 'CS' with its corresponding value from b. The output will be [{'Gfg': 6, 'is': 9, 'best': 10, 'CS': 6}, {'Gfg': 8, 'is': 11, 'best': 19, 'CS': 7} .
List comprehension is the most efficient way as it allows us to iterate over the list of dictionaries and add a new key-value pair to each dictionary concisely. It's widely preferred for its readability and performance.
Output
[{'Gfg': 6, 'is': 9, 'best': 10, 'CS': 6}, {'Gfg': 8, 'is': 11, 'best': 19, 'CS': 7}, {'Gfg': 2, 'is': 16, 'best': 10, 'CS': 4}, {'Gfg': 12, 'is': 1, 'best': 8, 'CS': 3},
{'Gfg': 22, 'is': 6, 'best': 8, 'CS': 9}]
Explanation:
Table of Content
map() applies a function defined using lambda to each dictionary in the list. It works similarly to list comprehension but may be less familiar for some.
Output
[{'Gfg': 6, 'is': 9, 'best': 10, 'CS': 6}, {'Gfg': 8, 'is': 11, 'best': 19, 'CS': 7}, {'Gfg': 2, 'is': 16, 'best': 10, 'CS': 4}, {'Gfg': 12, 'is': 1, 'best': 8, 'CS': 3},
{'Gfg': 22, 'is': 6, 'best': 8, 'CS': 9}]
Explanation:
While this approach can also work, it's less efficient compared to the other methods. It involves pairing the dictionaries with the values and then constructing new dictionaries, which can introduce overhead.
Output
[{'Gfg': 6, 'is': 9, 'best': 10, 'CS': 6}, {'Gfg': 8, 'is': 11, 'best': 19, 'CS': 7}, {'Gfg': 2, 'is': 16, 'best': 10, 'CS': 4}, {'Gfg': 12, 'is': 1, 'best': 8, 'CS': 3},
{'Gfg': 22, 'is': 6, 'best': 8, 'CS': 9}]
Explanation:
Loop is the traditional approach, where we loop through the list and use the update() method to add the new key-value pair. This method is simple and works well if we're more comfortable with straightforward programming style.
Output
[{'Gfg': 6, 'is': 9, 'best': 10, 'CS': 6}, {'Gfg': 8, 'is': 11, 'best': 19, 'CS': 7}, {'Gfg': 2, 'is': 16, 'best': 10, 'CS': 4}, {'Gfg': 12, 'is': 1, 'best': 8, 'CS': 3},
{'Gfg': 22, 'is': 6, 'best': 8, 'CS': 9}]
Explanation: