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 Tutorial | Learn Python Programming Language Python Tutorial â 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.Python is:A high-level language, used in web development, data science, automatio
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
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
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
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
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
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read