Saturday, September 21, 2024
Google search engine
HomeLanguagesPython | Merging two Dictionaries

Python | Merging two Dictionaries

There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Python. In this article, we will discuss a few ways of merging dictionaries. 

Using the method update() 

By using the method update() in Python, one list can be merged into another. But in this, the second list is merged into the first list and no new list is created. It returns None

Example: 

Python3




# Python code to merge dict using update() method
def Merge(dict1, dict2):
    return(dict2.update(dict1))
 
 
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
 
# This returns None
print(Merge(dict1, dict2))
 
# changes made in dict2
print(dict2)


Output:

None
{'c': 4, 'a': 10, 'b': 8, 'd': 6}

Time complexity: O(1) 
Auxiliary space: O(1)

This is generally considered a trick in Python where a single expression is used to merge two dictionaries and stored in a third dictionary. The single expression is **. This does not affect the other two dictionaries. ** implies that an argument is a dictionary. Using ** [double star] is a shortcut that allows you to pass multiple arguments to a function directly using a dictionary. For more information refer **kwargs in Python. Using this we first pass all the elements of the first dictionary into the third one and then pass the second dictionary into the third. This will replace the duplicate keys of the first dictionary. 
Example: 

Python3




# Python code to merge dict using a single
# expression
def Merge(dict1, dict2):
    res = {**dict1, **dict2}
    return res
     
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
dict3 = Merge(dict1, dict2)
print(dict3)


Output

{'a': 10, 'b': 8, 'd': 6, 'c': 4}

Time complexity: O(1). The time complexity of merging two dictionaries using the single expression method is constant time, denoted as O(1). 

Auxiliary space complexity: O(n). The auxiliary space complexity of this method depends on the total number of key-value pairs in both input dictionaries. 

Using | in Python 3.9

In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.

Example:

Python3




# code
# Python code to merge dict using a single 
# expression
def Merge(dict1, dict2):
    res = dict1 | dict2
    return res
       
# Driver code
dict1 = {'x': 10, 'y': 8}
dict2 = {'a': 6, 'b': 4}
dict3 = Merge(dict1, dict2)
print(dict3)
 
# This code is contributed by virentanti16


Output:

{'x': 10, 'a': 6,  'b': 4, 'y': 8}

Time complexity: O(1)
Auxiliary space: O(N)

Using for loop and keys() method

Python3




# code
# Python code to merge dictionary
def Merge(dict1, dict2):
    for i in dict2.keys():
        dict1[i]=dict2[i]
    return dict1
     
# Driver code
dict1 = {'x': 10, 'y': 8}
dict2 = {'a': 6, 'b': 4}
dict3 = Merge(dict1, dict2)
print(dict3)
 
# This code is contributed by Bhavya Koganti


Output

{'x': 10, 'y': 8, 'a': 6, 'b': 4}

One new approach to merge dictionaries in Python is to use the built-in ChainMap class from the collections module. This class allows you to create a single view of multiple dictionaries, and any updates or changes made to the ChainMap will be reflected in the underlying dictionaries.

Here’s an example of how to use ChainMap to merge two dictionaries:

Python3




from collections import ChainMap
 
# create the dictionaries to be merged
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
 
# create a ChainMap with the dictionaries as elements
merged_dict = ChainMap(dict1, dict2)
 
# access and modify elements in the merged dictionary
print(merged_dict['a'])  # prints 1
print(merged_dict['c'])  # prints 3
merged_dict['c'] = 5  # updates value in dict2
print(merged_dict['c'])  # prints 5
 
# add a new key-value pair to the merged dictionary
merged_dict['e'] = 6  # updates dict1
print(merged_dict['e'])  # prints 6


Output

1
3
5
6

Using ChainMap to merge dictionaries is a concise and efficient way to combine multiple dictionaries, and allows you to easily update and modify the merged dictionary.

Using dict constructor:

Python3




def merge_dictionaries(dict1, dict2):
    merged_dict = dict1.copy()
    merged_dict.update(dict2)
    return merged_dict
 
# Driver code
dict1 = {'x': 10, 'y': 8}
dict2 = {'a': 6, 'b': 4}
 
print(merge_dictionaries(dict1, dict2))


Output

{'x': 10, 'y': 8, 'a': 6, 'b': 4}

Time Complexity: O(N)
Auxiliary Space: O(N)

Method #5: Using the dict() constructor with the union operator (|)

This method uses the dict() constructor with the union operator (|) to merge two dictionaries. The union operator combines the keys and values of the two dictionaries, and any common keys in the two dictionaries take the value from the second dictionary.

  • Define the Merge() function that takes two dictionaries (dict1 and dict2) as input.
  • Use the items() method to get the key-value pairs of both dictionaries, and merge them using the union operator (|).
  • Use the dict() constructor to create a new dictionary from the merged items.
  • Return the merged dictionary.
  • In the driver code, define two dictionaries (dict1 and dict2) with some key-value pairs.
  • Call the Merge() function with the two dictionaries as input, and assign the returned merged dictionary to a new variable (merged_dict).
  • Print the merged dictionary.

Python3




# method to merge two dictionaries using the dict() constructor with the union operator (|)
def Merge(dict1, dict2):
    # create a new dictionary by merging the items of the two dictionaries using the union operator (|)
    merged_dict = dict(dict1.items() | dict2.items())
    # return the merged dictionary
    return merged_dict
 
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
 
# merge the two dictionaries using the Merge() function
merged_dict = Merge(dict1, dict2)
 
# print the merged dictionary
print(merged_dict)


Output

{'d': 6, 'b': 8, 'c': 4, 'a': 10}

Time complexity: O(n), where n is the total number of key-value pairs in both dictionaries. This is because we need to iterate over all the key-value pairs in both dictionaries to merge them using the union operator.
Auxiliary Space: O(n), where n is the total number of key-value pairs in both dictionaries

Method #6: Using reduce():
Algorithm :

  1. Import the reduce() function from the functools module.
  2. Define a function merge_dictionaries(dict1, dict2) that takes two dictionaries as arguments and returns their merge.
  3. Define two dictionaries dict1 and dict2 with some key-value pairs.
  4. Put the dictionaries dict1 and dict2 into a list dict_list.
  5. Call the reduce() function with the merge_dictionaries function and the dict_list list as arguments.
  6. Print the resulting merged dictionary.

Python3




from functools import reduce
 
def merge_dictionaries(dict1, dict2):
    merged_dict = dict1.copy()
    merged_dict.update(dict2)
    return merged_dict
 
 
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
 
dict_list = [dict1, dict2]  # Put the dictionaries into a list
 
result_dict = reduce(merge_dictionaries, dict_list)
 
print(result_dict)
#This code is contributed by Rayudu.


Output

{'a': 10, 'b': 8, 'd': 6, 'c': 4}

The time complexity :O(n), where n is the number of dictionaries in the dict_list list. This is because the merge_dictionaries() function is called once for each pair of dictionaries in the list. Since there are n-1 pairs of dictionaries in the list, the merge_dictionaries() function is called n-1 times.

The space complexity : O(m), where m is the total number of key-value pairs in all the dictionaries. This is because the merge_dictionaries() function creates a new dictionary that contains all the key-value pairs from both input dictionaries. Therefore, the size of the merged dictionary is proportional to the total number of key-value pairs in the input dictionaries.

Previous article
Next article
RELATED ARTICLES

Most Popular

Recent Comments