Open In App

Python program to update a dictionary with the values from a dictionary list

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

Given a dictionary and dictionary list, update the dictionary with dictionary list values.

Input : test_dict = {“Gfg” : 2, “is” : 1, “Best” : 3}, dict_list = [{‘for’ : 3, ‘all’ : 7}, {‘and’ : 1, ‘CS’ : 9}] 
Output : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7, ‘and’: 1, ‘CS’: 9} 
Explanation : All dictionary keys updated in single dictionary.

Input : test_dict = {“Gfg” : 2, “is” : 1, “Best” : 3}, dict_list = [{‘for’ : 3, ‘all’ : 7}] 
Output : {‘Gfg’: 2, ‘is’: 1, ‘Best’: 3, ‘for’: 3, ‘all’: 7} 
Explanation : All dictionary keys updated in single dictionary. 

Method #1 : Using update() + loop

In this, we iterate through all the elements in loop, and perform update to update all the keys in dictionary to original dictionary.

Step-by-step approach :

  • First, initialize a dictionary test_dict with some key-value pairs.
  • Print the original dictionary.
  • Initialize a list of dictionaries dict_list.
  • Use a for loop to iterate through the dict_list.
  • Inside the loop, use the update() method to update the test_dict with the current dictionary dicts in the loop.
  • Print the updated dictionary test_dict.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Update dictionary with dictionary list
# Using update() + loop
 
# initializing dictionary
test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing dictionary list
dict_list = [{'for' : 3, 'all' : 7}, {'geeks' : 10}, {'and' : 1, 'CS' : 9}]
 
for dicts in dict_list:
     
    # updating using update()
    test_dict.update(dicts)
 
# printing result
print("The updated dictionary : " + str(test_dict))


Output

The original dictionary is : {'Gfg': 2, 'is': 1, 'Best': 3}
The updated dictionary : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'geeks': 10, 'and': 1, 'CS': 9}

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

Method #2 : Using ChainMap + ** operator

In this, we perform task of merging all list dictionaries into 1 using ChainMap and ** operator is used to merge target dictionary to merged dictionary.

Python3




# Python3 code to demonstrate working of
# Update dictionary with dictionary list
# Using ChainMap + ** operator
from collections import ChainMap
 
# initializing dictionary
test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing dictionary list
dict_list = [{'for' : 3, 'all' : 7}, {'geeks' : 10}, {'and' : 1, 'CS' : 9}]
 
# ** operator extracts keys and re initiates.
# ChainMap is used to merge dictionary list
res = {**test_dict, **dict(ChainMap(*dict_list))}
 
# printing result
print("The updated dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 2, 'is': 1, 'Best': 3}
The updated dictionary : {'Gfg': 2, 'is': 1, 'Best': 3, 'and': 1, 'CS': 9, 'geeks': 10, 'for': 3, 'all': 7}

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

Method 3: Using dictionary comprehension.

Using dictionary comprehension to create a new dictionary from the list of dictionaries. We are using the unpacking operator (**), which unpacks the key-value pairs from both dictionaries into a single dictionary.

Follow the below steps to implement the above idea:

  • Initialize the original dictionary.
  • Print the original dictionary.
  • Initialize the list of dictionaries.
  • Use dictionary comprehension to create a new dictionary by iterating through each dictionary in the list of dictionaries and unpacking its key-value pairs.
  • Use the unpacking operator (**) to merge the new dictionary with the original dictionary and create the updated dictionary.
  • Print the updated dictionary.

Below is the implementation of the above approach:

Python3




# initializing dictionary
test_dict = {"Gfg": 2, "is": 1, "Best": 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing dictionary list
dict_list = [{'for': 3, 'all': 7}, {'geeks': 10}, {'and': 1, 'CS': 9}]
 
# Using dictionary comprehension to update the dictionary
test_dict = {**test_dict, **
             {key: val for dicts in dict_list for key, val in dicts.items()}}
 
# printing result
print("The updated dictionary : " + str(test_dict))


Output

The original dictionary is : {'Gfg': 2, 'is': 1, 'Best': 3}
The updated dictionary : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'geeks': 10, 'and': 1, 'CS': 9}

Time complexity: O(nm), where n is the length of the list of dictionaries and m is the average number of key-value pairs in each dictionary.
Auxiliary space: O(nm), as we are creating a new dictionary to store the updated key-value pairs.

Method 4: Using a list comprehension and the update() 

Step-by-step approach:

  • Create the original test_dict dictionary with 3 key-value pairs.
  • Print the original dictionary using the print() function and the str() method to convert the dictionary to a string.
  • Create a list of dictionaries named dict_list with 3 dictionaries containing key-value pairs.
  • Use a list comprehension to iterate over each dictionary in the dict_list and update the test_dict with the update() method.
  • Print the updated dictionary using the print() function and the str() method to convert the dictionary to a string.

Python3




# initializing dictionary
test_dict = {"Gfg": 2, "is": 1, "Best": 3}
 
# printing original dictionary
print("The original dictionary is: " + str(test_dict))
 
# initializing dictionary list
dict_list = [{'for': 3, 'all': 7}, {'geeks': 10}, {'and': 1, 'CS': 9}]
 
# Using list comprehension and update() method to update the dictionary
[test_dict.update(d) for d in dict_list]
 
# printing result
print("The updated dictionary: " + str(test_dict))


Output

The original dictionary is: {'Gfg': 2, 'is': 1, 'Best': 3}
The updated dictionary: {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'geeks': 10, 'and': 1, 'CS': 9}

Time complexity: O(n*m), where n is the length of the dict_list and m is the average length of the dictionaries in dict_list.
Auxiliary space: O(1), since the only extra space used is for the test_dict dictionary and the dict_list list, both of which are already initialized.

Method 5: Using a for loop to iterate over the dictionary list and its items and adding them to the original dictionary

Step-by-step approach:

  • Initialize the original dictionary with some key-value pairs.
  • Print the original dictionary to verify the initial values.
  • Initialize a list of dictionaries, where each dictionary contains key-value pairs to be added to the original dictionary.
  • Use a for loop to iterate over the list of dictionaries and their items, and add each key-value pair to the original dictionary.
  • Print the updated dictionary to verify that the new key-value pairs have been added.

Below is the implementation of the above approach:

Python3




# initializing dictionary
test_dict = {"Gfg": 2, "is": 1, "Best": 3}
 
# printing original dictionary
print("The original dictionary is: " + str(test_dict))
 
# initializing dictionary list
dict_list = [{'for': 3, 'all': 7}, {'geeks': 10}, {'and': 1, 'CS': 9}]
 
# Using for loop to update the dictionary
for d in dict_list:
    for key, value in d.items():
        test_dict[key] = value
 
# printing result
print("The updated dictionary: " + str(test_dict))


Output

The original dictionary is: {'Gfg': 2, 'is': 1, 'Best': 3}
The updated dictionary: {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'geeks': 10, 'and': 1, 'CS': 9}

Time complexity: O(N*M), where N is the length of the dictionary list and M is the average number of key-value pairs in each dictionary in the list.
Auxiliary space: O(1), as we are only modifying the original dictionary in place and not creating any additional data structures.

Method 6: Using the built-in function reduce() from the functools module and a lambda function

Step-by-step approach :

  • Import the functools module.
  • Define the lambda function to update the dictionary.
  • Apply reduce() to the list of dictionaries. The reduce() function applies the lambda function to the test_dict and each dictionary in dict_list in turn, updating the test_dict each time.
  • Print the updated dictionary.

Below is the implementation of the above approach:

Python3




# Import functools module
from functools import reduce
 
# Define lambda function
update_dict = lambda x, y: x.update(y) or x
 
# Initializing dictionary
test_dict = {"Gfg": 2, "is": 1, "Best": 3}
 
# Print original dictionary
print("The original dictionary is: " + str(test_dict))
 
# Initializing dictionary list
dict_list = [{'for': 3, 'all': 7}, {'geeks': 10}, {'and': 1, 'CS': 9}]
 
# Using reduce and lambda function to update the dictionary
test_dict = reduce(update_dict, dict_list, test_dict)
 
# Print the updated dictionary
print("The updated dictionary: " + str(test_dict))


Output

The original dictionary is: {'Gfg': 2, 'is': 1, 'Best': 3}
The updated dictionary: {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'geeks': 10, 'and': 1, 'CS': 9}

Time complexity: O(nm), where n is the length of dict_list and m is the maximum number of key-value pairs in any dictionary in dict_list.
Auxiliary space: O(1), because we are updating the original dictionary in place and not creating any new data structures.



Similar Reads

Python | Even values update in dictionary
Sometimes, while working with dictionaries, we might come across a problem in which we require to perform a particular operation on even value of keys. This type of problem can occur in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop This is the naive method in which this task can be pe
3 min read
Python - Dictionary Tuple values update
Sometimes, while working with Tuple data, we can have problem when we perform its editions, reason being it's immutability. This discusses the editions in tuple values in dictionary. This can have application in many domains as dictionary is often popular data type in web development and Data Science domains. Let's discuss certain ways in which thi
3 min read
Python - Update dictionary with other dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the update of dictionary with other keys of dictionary. This can have applications in domains in which we need to add certain records to previously captured records. Let's discuss certain ways in which this task can be performed. Method #1 : Using loo
9 min read
Python - Update values of a list of dictionaries
In this article, we will update the values of a list of dictionaries. Method 1: Using append() function The append function is used to insert a new value in the list of dictionaries, we will use pop() function along with this to eliminate the duplicate data. Syntax: dictionary[row]['key'].append('value')dictionary[row]['key'].pop(position) Where: d
3 min read
Python - Split Dictionary values on size limit of values
Given a dictionary with string values, the task is to write a python program to split values if the size of string exceeds K. Input : {1 : "Geeksforgeeks", 2 : "best for", 3 : "all geeks"}, limit = 5Output : {1: 'Geeks', 2: 'forge', 3: 'eks', 4: 'best ', 5: 'for', 6: 'all g', 7: 'eeks'}Explanation : All string values are capped till length 5. New v
8 min read
Python - Extract Unique values dictionary values
Sometimes, while working with data, we can have problem in which we need to perform the extraction of only unique values from dictionary values list. This can have application in many domains such as web development. Lets discuss certain ways in which this task can be performed. Extract Unique values dictionary values Using sorted() + set comprehen
7 min read
Python - Remove duplicate values across Dictionary Values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the duplicate values across all the dictionary value lists. This problem can have applications in data domains and web development domains. Let's discuss certain ways in which this task can be performed. Input: test_dict = {'Manjeet': [1], 'Akash
8 min read
Python - Test for Even values dictionary values lists
Given a dictionary with lists as values, map Boolean values depending upon all values in List are Even or not. Input : {"Gfg" : [6, 8, 10], "is" : [8, 10, 12, 16], "Best" : [10, 16, 14, 6]} Output : {'Gfg': True, 'is': True, 'Best': True} Explanation : All lists have even numbers. Input : {"Gfg" : [6, 5, 10], "is" : [8, 10, 11, 16], "Best" : [10, 1
8 min read
Python - Extract Dictionary values list to List
Sometimes, while working with dictionary records, we can have problems in which we need to extract all the dictionary values into a single separate list. This can have possible application in data domains and web-development. Lets discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression The combinatio
5 min read
Python - Assigning Key values to list elements from Value list Dictionary
Given a List of elements, map them with keys of matching values from a value list. Input : test_list = [4, 6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4]} Output : ['is', 'Gfg', 'Gfg', 'Gfg', 'Gfg'] Explanation : 4 is present in "is" key, hence mapped in new list. Input : test_list = [6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" :
7 min read
Practice Tags :
three90RightbarBannerImg