Open In App

Python – Add custom values key in List of dictionaries

Last Updated : 21 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of dictionaries, custom list, and Key, add the key to each dictionary with list values in order.

Input : test_list = [{"Gfg" : 6, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, 
                    {"Gfg" : 2, "is" : 16, "best" : 10}], K = "Geeks", append_list = [6, 7, 4] 
Output : [{"Gfg" : 6, "is" : 9, "best" : 10, "Geeks" : 6}, {"Gfg" : 8, "is" : 11, "best" : 19, 
           "Geeks" : 7}, {"Gfg" : 2, "is" : 16, "best" : 10, "Geeks" : 4}] 
Explanation : "Geeks" key added in each dictionary. 
Input : test_list = [{"Gfg" : 6, "is" : 9, "best" : 10}], K = "CS", append_list = [6] 
Output : [{"Gfg" : 6, "is" : 9, "best" : 10, "CS" : 6}] 
Explanation : "CS" key added in each dictionary with 6 as value.

Method #1 : Using loop + enumerate()

This is one of the ways in which this task can be performed. In this, we iterate through the dictionary using enumerate() to get indices and keep assigning each dictionary key with its index value.

Python3




# Python3 code to demonstrate working of
# Add custom values key in List of dictionaries
# Using loop
 
# initializing lists
test_list = [{"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}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing Key
K = "CS"
 
# initializing list
append_list = [6, 7, 4, 3, 9]
 
# using enumerate() to iterate for index and values
for idx, ele in enumerate(test_list):
        ele[K] = append_list[idx]
 
# printing result
print("The dictionary list after addition : " + str(test_list))


Output

The original list : [{'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}]
The dictionary list after addition : [{'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}]

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2 : Using zip() + loop

This is yet another way in which this task can be performed. In this, we perform mapping of list values with each dictionary using zip().

Python3




# Python3 code to demonstrate working of
# Add custom values key in List of dictionaries
# Using zip() + loop
 
# initializing lists
test_list = [{"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}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing Key
K = "CS"
 
# initializing list
append_list = [6, 7, 4, 3, 9]
 
# zip() used to bind index wise
# list and dictionary
for dic, lis in zip(test_list, append_list):
    dic[K] = lis
 
# printing result
print("The dictionary list after addition : " + str(test_list))


Output

The original list : [{'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}]
The dictionary list after addition : [{'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}]

Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(1), since the additional space used is constant and does not depend on the input size.

Method 3: using the map() function along with lambda function

The above code uses the lambda function to iterate over each element of the test_list and the append_list simultaneously and adds the key-value pair to each dictionary in test_list. The ** operator is used to unpack the original dictionary and the new key-value pair into a new dictionary. Finally, the map() function returns a list of modified dictionaries.

  1. Create a list of dictionaries named test_list, where each dictionary contains three key-value pairs.
  2. Print the original list test_list.
  3. Initialize a variable K with the string value “CS”.
  4. Create another list named append_list, which contains five integer values.
  5. Use the map() function with a lambda function to iterate over the test_list and append_list lists in parallel.
  6. In each iteration of the map() function, the lambda function combines the current dictionary from the test_list with the current integer from the append_list into a new dictionary that contains all the key-value pairs from the original dictionary plus a new key-value pair with the key K and the value of the current integer.
  7. The map() function returns a new list of dictionaries with the updated key-value pairs.
  8. Convert the updated list of dictionaries to a Python list using the list() function.
  9. Print the final result, which is the updated list of dictionaries with the added key-value pairs.

Python3




# initializing lists
test_list = [{"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}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing Key
K = "CS"
 
# initializing list
append_list = [6, 7, 4, 3, 9]
 
# using map() function with lambda to add key-value pairs
test_list = list(map(lambda x, y: {**x, K: y}, test_list, append_list))
 
# printing result
print("The dictionary list after addition : " + str(test_list))


Output

The original list : [{'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}]
The dictionary list after addition : [{'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}]

Time complexity: O(n), where n is the length of the test_list or the append_list.
Auxiliary space: O(n) As well, as due to the creation of a new list of modified dictionaries.

Method 4: Using list comprehension with the enumerate() function.

Step-by-step approach:

  • Initialize the original list of dictionaries and the key and values to be added to the list.
  • Create a list comprehension to iterate over each dictionary in the list and add the key-value pair to it using the enumerate() function to access the corresponding value from the append_list.
  • Print the updated list of dictionaries.

Below is the implementation of the above approach:

Python3




# initializing lists
test_list = [{"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}]
 
# initializing Key and list
K = "CS"
append_list = [6, 7, 4, 3, 9]
 
# using list comprehension with enumerate() to add key-value pair to each dictionary
test_list = [{**d, K: v} for d, v in zip(test_list, append_list)]
 
# printing result
print("The dictionary list after addition : " + str(test_list))


Output

The dictionary list after addition : [{'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}]

Time complexity: O(n), where n is the number of dictionaries in the list.
Auxiliary space: O(n), where n is the number of dictionaries in the list.

Method 5: Using the itertools library:

Steps:

  1. Import the itertools library.
  2. Initialize the list of dictionaries and the list to append as values.
  3. Define the key to add to the dictionary.
  4. Use the itertools.zip_longest() function to iterate over both lists simultaneously.
  5. Use dictionary comprehension to create a new dictionary with the original dictionary’s keys and values plus the new key-value pair.
  6. Assign the updated dictionaries back to the original list.
  7. Print the updated list of dictionaries.

Python3




# Import itertools library
import itertools
 
# Initialize the lists
test_list = [{"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}]
 
# Initialize Key and list
K = "CS"
append_list = [6, 7, 4, 3, 9]
 
# using itertools.zip_longest() to
# add key-value pair to each dictionary
test_list = [{**d, K: v}
             for d, v in itertools.zip_longest(test_list, append_list, fillvalue=0)]
 
# printing result
print("The dictionary list after addition : " + str(test_list))


Output

The dictionary list after addition : [{'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}]

Time Complexity: O(N), where N is the length of the list of dictionaries.
Auxiliary Space: O(1), since we are updating the original list in place and not creating any new data structures.

Method #6: Using the pandas library.

Step-by-step approach:

  • Import the pandas library.
  • Convert the original list of dictionaries into a pandas DataFrame.
  • Create a new Series object from the append_list.
  • Add the new Series to the DataFrame using the Key as the name of the new Series.
  • Convert the DataFrame back into a list of dictionaries using the to_dict() method.

Python3




# import pandas library
import pandas as pd
 
# initializing lists
test_list = [{"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}]
 
# initializing Key
K = "CS"
 
# initializing list
append_list = [6, 7, 4, 3, 9]
 
# convert the original list to a pandas DataFrame
df = pd.DataFrame(test_list)
 
# create a new Series from the append_list
new_column = pd.Series(append_list)
 
# add the new Series to the DataFrame using the Key as the name of the new column
df[K] = new_column
 
# convert the DataFrame back into a list of dictionaries
test_list = df.to_dict(orient='records')
 
# print the resulting list of dictionaries
print("The dictionary list after addition : " + str(test_list))


OUTPUT :
 The dictionary list after addition : [{'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}]

Time complexity for this method would be O(n) where n is the number of elements in the list of dictionaries. 
The auxiliary space complexity would be O(n) as well, as we need to create a new DataFrame and Series objects.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads