Open In App

Python – Update dictionary with other dictionary

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

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 loop This is a brute force way in which this task can be performed. In this, we check for keys in other dictionary, and add the items in new dictionary. 

Python3




# Python3 code to demonstrate working of
# Update dictionary with other dictionary
# Using loop
 
# initializing dictionaries
test_dict1 = {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
test_dict2 = {'for': 3, 'geeks': 5}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# Update dictionary with other dictionary
# Using loop
for key in test_dict1:
    if key in test_dict2:
        test_dict1[key] = test_dict2[key]
 
# printing result
print("The updated dictionary is : " + str(test_dict1))


Output : 

The original dictionary 1 is : {‘best’: 2, ‘for’: 4, ‘gfg’: 1, ‘geeks’: 6} The original dictionary 2 is : {‘for’: 3, ‘geeks’: 5} The updated dictionary is : {‘best’: 2, ‘for’: 3, ‘gfg’: 1, ‘geeks’: 5}

  Method #2 : Using dictionary comprehension This is yet another way in which this task can be performed. In this, we iterate for dictionary and perform update in single line using comprehension. 

Python3




# Python3 code to demonstrate working of
# Update dictionary with other dictionary
# Using dictionary comprehension
 
# initializing dictionaries
test_dict1 = {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
test_dict2 = {'for': 3, 'geeks': 5}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# Update dictionary with other dictionary
# Using dictionary comprehension
res = {key: test_dict2.get(key, val) for key, val in test_dict1.items()}
 
# printing result
print("The updated dictionary is : " + str(res))


Output : 

The original dictionary 1 is : {‘best’: 2, ‘for’: 4, ‘gfg’: 1, ‘geeks’: 6} The original dictionary 2 is : {‘for’: 3, ‘geeks’: 5} The updated dictionary is : {‘best’: 2, ‘for’: 3, ‘gfg’: 1, ‘geeks’: 5}

The time complexity of the given program is O(N), where N is the total number of keys in both the dictionaries. 

The space complexity of the program is also O(N), where N is the number of keys in test_dict1.

Method #3 : Using update() method

Python3




# Python3 code to demonstrate working of
# Update dictionary with other dictionary
# Using loop
 
# initializing dictionaries
test_dict1 = {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
test_dict2 = {'for': 3, 'geeks': 5}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# Update dictionary with other dictionary
# Using loop
test_dict1.update(test_dict2)
 
# printing result
print("The updated dictionary is : " + str(test_dict1))


Output

The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
The original dictionary 2 is : {'for': 3, 'geeks': 5}
The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'geeks': 5}

Time Complexity : O(N)

Auxiliary Space : O(N)

Method #4: Using the’ **’ operator: The ‘**’ operator 

  1. Define the two dictionaries:
  2. Print the original dictionaries to verify their contents:
  3. Use the “**” operator to combine the dictionaries into a new dictionary:
  4. Print the updated dictionary to verify the combination:
  5. The output should show the updated dictionary with the combined key-value pairs:

Example:

Python3




# Define the two dictionaries
test_dict1 = {'gfg' : 1, 'best' : 2, 'for' : 4, 'geeks' : 6}
test_dict2 = {'for' : 3, 'geeks' : 5}
 
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Use the "**" operator to combine the dictionaries
# The "**" operator is used to unpack dictionaries and pass the key-value pairs as separate arguments to a function
# In this case, we are using the "**" operator to unpack the dictionaries and add their key-value pairs to a new dictionary
 
test_dict1 = {**test_dict1, **test_dict2}
 
# Print the combined dictionary
print("The updated dictionary is : " + str(test_dict1))
# Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}


Output

The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
The original dictionary 2 is : {'for': 3, 'geeks': 5}
The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'geeks': 5}

Time Complexity: Creating the DataFrame object takes O(n) time, where n is the length of the first list.
Extracting the values from the first list corresponding to the indices in the second list using the loc[] function takes O(m) time, where m is the length of the second list.

Converting the resulting series object to a list takes O(m) time.
Therefore, the overall time complexity of the algorithm is O(n+m).

Auxiliary Space Complexity: The algorithm uses O(n) auxiliary space to store the DataFrame object and O(m) auxiliary space to store the resulting list. Therefore, the overall auxiliary space complexity of the algorithm is O(n+m). Note that this assumes that the length of the resulting list is at most min(n,m); if the length of the resulting list can be greater than min(n,m), then the overall auxiliary space complexity would be O(max(n,m)).

Method #6: Using the dict() constructor and the update() method

Use the dict() constructor to create a copy of the first dictionary and then updates it with the second dictionary using the update() method. 

Python3




# Python3 code to demonstrate working of
# Update dictionary with other dictionary
# Using the dict() constructor and update() method
 
# initializing dictionaries
test_dict1 = {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
test_dict2 = {'for': 3, 'geeks': 5}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# Update dictionary with other dictionary
# Using the dict() constructor and update() method
new_dict = dict(test_dict1)
new_dict.update(test_dict2)
 
# printing result
print("The updated dictionary is : " + str(new_dict))


Output

The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
The original dictionary 2 is : {'for': 3, 'geeks': 5}
The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'geeks': 5}

Time complexity: O(N), where N is the total number of key-value pairs in both dictionaries.
Auxiliary space: O(N)

Method #7: Using reduce():

  1. Import the reduce() function from the functools module.
  2. Initialize the two dictionaries to be merged.
  3. Define a lambda function that takes two arguments: an accumulator dictionary and the next dictionary to merge, and returns a new dictionary that is the result of merging the accumulator dictionary with the next dictionary using the unpacking syntax **.
  4. Use the reduce() function to apply the lambda function to each dictionary in the list of dictionaries to be merged, starting with the first dictionary as the initial accumulator value.
  5. Return the final merged dictionary.

Python3




from functools import reduce
 
# initializing dictionaries
test_dict1 = {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
test_dict2 = {'for': 3, 'geeks': 5}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# Update dictionary with other dictionary using reduce
updated_dict = reduce(lambda acc, d: {**acc, **d}, [test_dict1, test_dict2])
 
# printing result
print("The updated dictionary is : " + str(updated_dict))
#This code is contributed by Jyothi pinjala.


Output

The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
The original dictionary 2 is : {'for': 3, 'geeks': 5}
The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'geeks': 5}

Time complexity:

The reduce() function is applied to each dictionary in the list, so the time complexity of the reduce() function is O(N), where N is the number of dictionaries in the list.
Merging two dictionaries using the unpacking syntax ** takes O(M) time, where M is the number of key-value pairs in the smaller dictionary.
Therefore, the total time complexity of the algorithm is O(N * M), where N is the number of dictionaries in the list and M is the maximum number of key-value pairs in any dictionary.

Auxiliary Space:

The space complexity of the algorithm depends on the size of the dictionaries being merged and the number of dictionaries in the list.
Since the lambda function returns a new dictionary every time it is called, the space complexity is proportional to the total size of the merged dictionary.
Therefore, the space complexity of the algorithm is O(K), where K is the total number of key-value pairs in all the dictionaries being merged.

Method #8: Using heapq:

  1. Create two dictionaries test_dict1 and test_dict2.
  2. Convert both dictionaries into tuples of (value, key) pairs with the help of a list comprehension.
  3. Create a list of the two tuple lists created above.
  4. Use the heapq.merge() function to merge the tuple lists.
  5. The merged tuples will be in ascending order of values, so we negate the values while merging to get the desired descending order.
  6. Convert the merged tuples back to a dictionary with the key as the second element of each tuple and the value as the negation of the first element of each tuple.
  7. Print the updated dictionary.

Python3




import heapq
 
# initializing dictionaries
test_dict1 = {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
test_dict2 = {'for': 3, 'geeks': 5}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# converting dictionaries to tuples of (value, key) pairs
dicts_tup = [(-val, key) for key, val in test_dict1.items()] + [(-val, key) for key, val in test_dict2.items()]
 
# merging dictionaries using heapq.merge function
merged_dict_tup = heapq.merge(dicts_tup)
updated_dict = {key: -val for val, key in merged_dict_tup}
 
# printing result
print("The updated dictionary is : " + str(updated_dict))
#This code is contributed by Pushpa.


Output

The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'geeks': 6}
The original dictionary 2 is : {'for': 3, 'geeks': 5}
The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'geeks': 5}

Time Complexity: O((n + m)log(n + m)) where n and m are the sizes of test_dict1 and test_dict2 respectively, due to the time taken to convert the dictionaries to tuples and merge the tuple lists using heapq.merge.

Space Complexity: O(n + m) due to the space taken by the two tuple lists.



Similar Reads

Python program to update a dictionary with the values from a dictionary list
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. I
8 min read
Python - Replace dictionary value from other dictionary
Given two dictionaries, update the values from other dictionary if key is present in other dictionary. Input : test_dict = {"Gfg" : 5, "is" : 8, "Best" : 10, "for" : 8, "Geeks" : 9}, updict = {"Geeks" : 10, "Best" : 17} Output : {'Gfg': 5, 'is': 8, 'Best': 17, 'for': 8, 'Geeks': 10} Explanation : "Geeks" and "Best" values updated to 10 and 17. Inpu
6 min read
Python Dictionary update() method
Python Dictionary update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs. Example: Original dictionary : {'A': 'Geeks', 'B': 'For'}Updated dictionary : {'A': 'Geeks', 'B': 'Geeks'}Original dictionary : {'A': 'Geeks', 'B': 'For'}Updated dictionary : {'A': 'Geeks', 'B': 'For', 'C
3 min read
Python: Update Nested Dictionary
A Dictionary in Python works similar to the Dictionary in the real world. Keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key-values can be repeated and be of any type. Refer to the below article to get the idea about dictionaries: Python Dictionary Nested Dictionary: The nested diction
6 min read
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 - Variable Operations Dictionary update
Sometimes, while working with Python dictionaries we can have a problem in which we need to perform a population of dictionary values using assigned variables after certain operation among them. This can have application in day-day programming. Let's discuss certain ways in which this task can be performed. Method #1 : Using lambda + dictionary com
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
Check and Update Existing Key in Python Dictionary
A dictionary in Python is an ordered collection of key-value pairs. Each key must be unique, and you can use various data types for both keys and values. Dictionaries are enclosed in curly braces {}, and the key-value pairs are separated by colons. Python Dictionary is mutable, meaning you can modify them in place. In this article, I have explained
3 min read
Python Update Dictionary Value by Key
A Dictionary in Python is an unordered collection of key-value pairs. Each key must be unique, and you can use various data types for both keys and values. Dictionaries are enclosed in curly braces {}, and the key-value pairs are separated by colons. Python dictionaries are mutable, meaning you can modify them in place. In this article, I have expl
3 min read
How to Update a Dictionary in Python
This article explores updating dictionaries in Python, where keys of any type map to values, focusing on various methods to modify key-value pairs in this versatile data structure. Update a Dictionary in PythonBelow, are the approaches to Update a Dictionary in Python: Using with Direct assignmentUsing the dict() constructorUsing the copy() and upd
3 min read
Practice Tags :
three90RightbarBannerImg