Python – Update dictionary with other dictionary
Last Updated :
22 Apr, 2023
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
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))
for key in test_dict1:
if key in test_dict2:
test_dict1[key] = test_dict2[key]
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
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))
res = {key: test_dict2.get(key, val) for key, val in test_dict1.items()}
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
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))
test_dict1.update(test_dict2)
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
- Define the two dictionaries:
- Print the original dictionaries to verify their contents:
- Use the “**” operator to combine the dictionaries into a new dictionary:
- Print the updated dictionary to verify the combination:
- The output should show the updated dictionary with the combined key-value pairs:
Example:
Python3
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))
test_dict1 = { * * test_dict1, * * test_dict2}
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: 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
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))
new_dict = dict (test_dict1)
new_dict.update(test_dict2)
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():
- Import the reduce() function from the functools module.
- Initialize the two dictionaries to be merged.
- 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 **.
- 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.
- Return the final merged dictionary.
Python3
from functools import reduce
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))
updated_dict = reduce ( lambda acc, d: { * * acc, * * d}, [test_dict1, test_dict2])
print ( "The updated dictionary is : " + str (updated_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:
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:
- Create two dictionaries test_dict1 and test_dict2.
- Convert both dictionaries into tuples of (value, key) pairs with the help of a list comprehension.
- Create a list of the two tuple lists created above.
- Use the heapq.merge() function to merge the tuple lists.
- The merged tuples will be in ascending order of values, so we negate the values while merging to get the desired descending order.
- 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.
- Print the updated dictionary.
Python3
import heapq
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))
dicts_tup = [( - val, key) for key, val in test_dict1.items()] + [( - val, key) for key, val in test_dict2.items()]
merged_dict_tup = heapq.merge(dicts_tup)
updated_dict = {key: - val for val, key in merged_dict_tup}
print ( "The updated dictionary is : " + str (updated_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 + 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.
Please Login to comment...