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 , 'Lazyroar' : 6 } test_dict2 = { 'for' : 3 , 'Lazyroar' : 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)) |
The original dictionary 1 is : {‘best’: 2, ‘for’: 4, ‘gfg’: 1, ‘Lazyroar’: 6} The original dictionary 2 is : {‘for’: 3, ‘Lazyroar’: 5} The updated dictionary is : {‘best’: 2, ‘for’: 3, ‘gfg’: 1, ‘Lazyroar’: 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 , 'Lazyroar' : 6 } test_dict2 = { 'for' : 3 , 'Lazyroar' : 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)) |
The original dictionary 1 is : {‘best’: 2, ‘for’: 4, ‘gfg’: 1, ‘Lazyroar’: 6} The original dictionary 2 is : {‘for’: 3, ‘Lazyroar’: 5} The updated dictionary is : {‘best’: 2, ‘for’: 3, ‘gfg’: 1, ‘Lazyroar’: 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 , 'Lazyroar' : 6 } test_dict2 = { 'for' : 3 , 'Lazyroar' : 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)) |
The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'Lazyroar': 6} The original dictionary 2 is : {'for': 3, 'Lazyroar': 5} The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'Lazyroar': 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
# Define the two dictionaries test_dict1 = { 'gfg' : 1 , 'best' : 2 , 'for' : 4 , 'Lazyroar' : 6 } test_dict2 = { 'for' : 3 , 'Lazyroar' : 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} |
The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'Lazyroar': 6} The original dictionary 2 is : {'for': 3, 'Lazyroar': 5} The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'Lazyroar': 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 , 'Lazyroar' : 6 } test_dict2 = { 'for' : 3 , 'Lazyroar' : 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)) |
The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'Lazyroar': 6} The original dictionary 2 is : {'for': 3, 'Lazyroar': 5} The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'Lazyroar': 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 # initializing dictionaries test_dict1 = { 'gfg' : 1 , 'best' : 2 , 'for' : 4 , 'Lazyroar' : 6 } test_dict2 = { 'for' : 3 , 'Lazyroar' : 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. |
The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'Lazyroar': 6} The original dictionary 2 is : {'for': 3, 'Lazyroar': 5} The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'Lazyroar': 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 # initializing dictionaries test_dict1 = { 'gfg' : 1 , 'best' : 2 , 'for' : 4 , 'Lazyroar' : 6 } test_dict2 = { 'for' : 3 , 'Lazyroar' : 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. |
The original dictionary 1 is : {'gfg': 1, 'best': 2, 'for': 4, 'Lazyroar': 6} The original dictionary 2 is : {'for': 3, 'Lazyroar': 5} The updated dictionary is : {'gfg': 1, 'best': 2, 'for': 3, 'Lazyroar': 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.