Python - Add custom values key in List of dictionaries
Last Updated :
25 Jan, 2025
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} .
Using list comprehension
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.
Python
a = [{"Gfg": 6, "is": 9, "best": 10},
{"Gfg": 8, "is": 11, "best": 19},
{"Gfg": 2, "is": 16, "best": 10},
{"Gfg": 12, "is": 1, "best": 8},
{"Gfg": 22, "is": 6, "best": 8}]
k = "CS" # initializing key
b = [6, 7, 4, 3, 9] # initializing append list
a = [{**ele, k: b[idx]} for idx, ele in enumerate(a)]
print(a)
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:
- enumerate(a) iterates through the list a and returning each dictionary ele with its index idx.
- {**ele, k: b[idx]} creates a new dictionary by unpacking ele and adding the key-value pair k: b[idx] where k is "CS" and b[idx] is the corresponding value from list b .
Using map()
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.
Python
a = [{"Gfg": 6, "is": 9, "best": 10},
{"Gfg": 8, "is": 11, "best": 19},
{"Gfg": 2, "is": 16, "best": 10},
{"Gfg": 12, "is": 1, "best": 8},
{"Gfg": 22, "is": 6, "best": 8}]
k = "CS" # initializing key
b = [6, 7, 4, 3, 9] # initializing append list
a = list(map(lambda d, idx: {**d, k: b[idx]}, a, range(len(a))))
print(a)
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:
- map() applies a lambda function to each dictionary d in a along with its index idx .
- {**d, k: b[idx]} creates a new dictionary by unpacking d and adding the key-value pair k: b[idx], where k is "CS" and b[idx] is the corresponding value from b.
Using zip()
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.
Python
a = [{"Gfg": 6, "is": 9, "best": 10},
{"Gfg": 8, "is": 11, "best": 19},
{"Gfg": 2, "is": 16, "best": 10},
{"Gfg": 12, "is": 1, "best": 8},
{"Gfg": 22, "is": 6, "best": 8}]
k = "CS" # initializing key
b = [6, 7, 4, 3, 9] # initializing append list
a = [dict(list(d.items()) + [(k, v)]) for d, v in zip(a, b)]
print(a)
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:
- zip(a, b) combines the list of dictionaries a with the list b into pairs, where each pair is a dictionary and its corresponding value from b.
- dict(list(d.items()) + [(k, v)]) for each pair (d, v), it gets the dictionary's key-value pairs with d.items(), appends the new key-value pair (k, v), and converts the updated list back into a dictionary using dict().
Using loop
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.
Python
a = [{"Gfg": 6, "is": 9, "best": 10},
{"Gfg": 8, "is": 11, "best": 19},
{"Gfg": 2, "is": 16, "best": 10},
{"Gfg": 12, "is": 1, "best": 8},
{"Gfg": 22, "is": 6, "best": 8}]
k = "CS"
b = [6, 7, 4, 3, 9]
for idx, ele in enumerate(a):
ele.update({k: b[idx]})
print(a)
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:
- enumerate(a) iterates through the list a, returning both the index idx and the dictionary ele .
- ele.update({k: b[idx]}) adds a new key-value pair to ele with key "CS" from k and value b[idx].
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
Dictionary keys as a list in Python In Python, we will encounter some situations where we need to extract the keys from a dictionary as a list. In this article, we will explore various easy and efficient methods to achieve this.Using list() The simplest and most efficient way to convert dictionary keys to lists is by using a built-in
2 min read
Python - Initialize dictionary with custom value list In python one usually comes across situations in which one has to use dictionary for storing the lists. But in those cases, one usually checks for first element and then creates a list corresponding to key when it comes. But its always wanted a method to initialize the dict. keys with a custom list.
4 min read
Create a List using Custom Key-Value Pair of a Dictionary - Python The task of creating a list using custom key-value pairs from a dictionary involves extracting the dictionaryâs keys and values and organizing them into a list of tuples. This allows for the flexibility of representing data in a sequence that maintains the relationship between keys and values.For ex
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