Adding Custom Values Key in a List of Dictionaries in Python



In this article, we will learn how to add a custom key with corresponding values to a list of dictionaries in Python.

Dictionaries in Python are collections of unordered items stored in the form of key-value pairs inside curly braces like this ?

Dictionary = {key: value,?.}

Suppose we have a list of dictionaries called dict_list and a key new_key, with its values provided in a separate list value_list. The goal is to add new_key to each dictionary in dict_list, assigning it the corresponding value from value_list.

Let's understand it with an example ?

#List of dictionary we have
dict_list:? [{'name': 'John','location': 'Hyderabad'},{'name': 'Jane',
'location': 'Bangalore'}]

#Key and values list we have
new_key = 'age'
value_list = [22, 23]

#On adding a custom key with its corresponding values from value_list, the desired output is 
Resultant list of dictionary:- [{'name': 'John',?location': ?Hyderabad','age': 22}, {'name': 'Jane', ?location': ?Hyderabad', 'age': 23}]

We can add custom key-value pair to each dictionary in a Python list of dictionary using the following approaches ?

  • Using enumerate() function with for loop
  • Using List Comprehension with enumerate() function
  • Using List Comprehension with zip() function
  • Using the map()

Let us go through this all one by one ?

Using enumerate() Function with For Loop

The enumerate function is used to add a counter to each item of an iterable in Python. We are using it to access the index and the dictionary at that index, while iterating over the list of dictionaries using a for loop. And then we add a new key-value pair to that dictionary.

Example

The following program prints the list of dictionaries containing new key-value pairs using the enumerate() function with a for loop in Python.

# Initializing dict_list, new_key, and value_list
dict_list = [{'name': 'John','location': 'Hyderabad'},{'name': 'Jane','location': 'Bangalore'}]

new_key = 'age'
value_list = [22, 23]

# Iterating over dict_list and 
# adding new key-value pair
for i, d in enumerate(dict_list):
   d[new_key] = value_list[i]
    
# Printing dict_list containing new key-value pair 
print(dict_list)

Output

[{'name': 'John', 'location': 'Hyderabad', 'age': 22}, {'name': 'Jane', 'location': 'Bangalore', 'age': 23}]

Using List Comprehension with enumerate() Function

List comprehension is a concise way of creating a list in Python, where we can perform an operation on each element of a given iterable object and store its resultant values as a list.

To add a custom key-value pair to each dictionary in a Python list of dictionaries, we need to pass the list as an iterable with the enumerate() function.

Using the enumerate() function, we are accessing the index and the dictionary at that index in a list of dictionaries. Then we add a new key-value pair to the accessed dictionary.

Example

The following program prints the list of dictionaries containing new key-value pairs using a list comprehension and the enumerate() function in Python.

# Initializing dict_list, new_key, and value_list
dict_list = [{'name': 'John','location': 'Hyderabad'},{'name': 'Jane','location': 'Bangalore'}]
new_key = 'age'
value_list = [22, 23]

# Iterating over dict_list and 
# adding new key-value pair

dict_list = [{**dic, new_key: value_list[idx]} for idx, dic in enumerate(dict_list)]
    
# Printing dict_list containing new key-value pair 
print(dict_list)

Output

[{'name': 'John', 'location': 'Hyderabad', 'age': 22}, {'name': 'Jane', 'location': 'Bangalore', 'age': 23}]

Using List Comprehension with zip() Function

Similar to the previous method (list comprehension with the enumerate() function), we can also use the zip() function instead of enumerate().

The zip() function in Python accepts variable number of iterable objects as parameters and rearranges the elements as per the index positions and returns them as an iterable.

This allows us to combine items from the dictionaries list and the values list, providing access to their dictionaries and values.

Example

The following program prints the list of dictionaries containing new key-value pairs using a list comprehension and the zip() function in Python.

# Initializing dict_list, new_key, and value_list
dict_list = [{'name': 'John', 'location': 'Hyderabad'},
            {'name': 'Jane', 'location': 'Bangalore'}]

new_key = 'age'
value_list = [22, 23]

# Adding new key-value pair using zip() and list comprehension
dict_list = [{**dic, new_key: val} for dic, val in zip(dict_list, value_list)]

# Printing dict_list containing new key-value pair 
print(dict_list)

Output

[{'name': 'John', 'location': 'Hyderabad', 'age': 22}, {'name': 'Jane', 'location': 'Bangalore', 'age': 23}]

Using the map() Function

The map() function in Python accepts two arguments, a function and an iterable, and returns a new iterable object by applying the specified function to each item of a given iterable.

To add a new key-value pair to a list of dictionaries, we need to pass the list of dictionaries as an iterable and a function to the map() function. This function adds a new key-value pair to each dictionary in the list of dictionaries.

Example

The following program prints the list of dictionaries containing new key-value pairs using the map() function in Python.

# Initializing dict_list, new_key, and value_list
dict_list = [{'name': 'John', 'location': 'Hyderabad'},
            {'name': 'Jane', 'location': 'Bangalore'}]

new_key = 'age'
value_list = [22, 23]

# Adding new key-value pair using map() with lambda
dict_list = list(map(lambda dic, idx: {**dic, new_key: value_list[idx]}, dict_list, range(len(dict_list))))

# Printing dict_list containing new key-value pair 
print(dict_list)

Output

[{'name': 'John', 'location': 'Hyderabad', 'age': 22}, {'name': 'Jane', 'location': 'Bangalore', 'age': 23}]

Conclusion

In this article, we have explored multiple methods for adding custom keys and values from another list to a list of dictionaries. List comprehension using both the enumerate() and zip() functions offers a concise way to achieve this, while the enumerate() function with for loop and the map() function provide a simpler approach.

Updated on: 2023-08-14T12:34:14+05:30

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements