Open In App

Python | Merging two Dictionaries

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, a dictionary is a data structure that contains the element in the key-value pair in which keys are used to access the values in the dictionary. Python has some inbuilt dictionaries like defaultdict. In this article, we will see various ways to merge two dictionaries.

Example

Input: dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
Output: {'a': 10, 'b': 8, 'd': 6, 'c': 4}

Merging Two Dictionaries in Python

There are various ways in which Dictionaries can be merged by using various functions and constructors in Python. Below are some following ways:

Python 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. In this example, we are using the update function to merge two dictionaries.

Python
# 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(n) 
Auxiliary space: O(1)

Python unpacking operator

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.

Python
# 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)
Auxiliary complexity: O(n)

Python Merge 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. In this example, we are using | operator to merge two dictionaries.

Python
# 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

In this example, we are using loop and key() method to merge two dictionaries.

Python
# 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}




Python Merge Dictionaries Using ChainMap Class

In this example, we are merging dictionaries in Python by using 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.

Python
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




Merge Two Dictionaries in Python Using dict constructor:

In this example, we are using dict constructor to merge two dictionaries.

Python
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)

Python Merge Dictionaries Using dict() constructor and 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.

Python
# 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.
Auxiliary Space: O(n), where n is the total number of key-value pairs in both dictionaries

Python Merge Two Dictionaries Using reduce():

In this example, we are merging two dictionaries using reduce() function. In this method, we define a merge function then takes two dictionaries as arguments and returns their merge.

Python
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}





Time complexity :O(n), where n is the number of dictionaries in the dict_list list.
Auxiliary complexity : O(m), where m is the total number of key-value pairs in all the dictionaries.

Python | Merging two Dictionaries – FAQs

Which statement is used to merge two dictionaries in Python?

To merge two dictionaries in Python, you can use the update() method or the ** unpacking operator (in Python 3.5 and later).

Using update() method:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

dict1.update(dict2)
print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}

Using the ** unpacking operator:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}

How to join dictionary values in Python?

To join dictionary values into a single string, you can use the join() method after converting the values to strings.

my_dict = {'a': 1, 'b': 2, 'c': 3}

# Join values into a single string
joined_values = ''.join(str(value) for value in my_dict.values())
print(joined_values) # Output: '123'

How to merge two dictionaries in Python with overwrite?

When merging two dictionaries using the update() method or the ** unpacking operator, the values from the second dictionary will overwrite those in the first dictionary for matching keys.

Using update() method:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

dict1.update(dict2)
print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4}

Using the ** unpacking operator:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

merged_dict = {**dict1, **dict2}
print(merged_dict) # Output: {'a': 1, 'b': 3, 'c': 4}

How to combine two lists of dictionaries?

To combine two lists of dictionaries, you can use the + operator to concatenate them.

list1 = [{'a': 1}, {'b': 2}]
list2 = [{'c': 3}, {'d': 4}]

combined_list = list1 + list2
print(combined_list) # Output: [{'a': 1}, {'b': 2}, {'c': 3}, {'d': 4}]




Previous Article
Next Article

Similar Reads

Python | Merging two list of dictionaries
Given two list of dictionaries, the task is to merge these two lists of dictionaries based on some value. Merging two list of dictionariesUsing defaultdict and extend to merge two list of dictionaries based on school_id. C/C++ Code # Python code to merge two list of dictionaries # based on some value. from collections import defaultdict # List init
6 min read
Python - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
6 min read
Python Program to extract Dictionaries with given Key from a list of dictionaries
Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value. Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3}], key= "gfg"Output : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}] Expl
6 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries
Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
3 min read
Python | Merging two strings with Suffix and Prefix
Given two strings A and B and these strings contain lower case letters. The task is to tell the length of the merged strings. For example, given A is "abcde" and B is "cdefg", then merging the two strings results in "abcdefg". The merge operation is performed in such a manner that the joining characters are both the suffix of A and Prefix of B. Bef
2 min read
Python Program For Merging Two Sorted Linked Lists Such That Merged List Is In Reverse Order
Given two linked lists sorted in increasing order. Merge them such a way that the result list is in decreasing order (reverse order). Examples: Input: a: 5->10->15->40 b: 2->3->20 Output: res: 40->20->15->10->5->3->2 Input: a: NULL b: 2->3->20 Output: res: 20->3->2Recommended: Please solve it on "PRACTIC
4 min read
Python | Difference in keys of two dictionaries
In this article, we will be given two dictionaries dic1 and dic2 which may contain the same keys and we have to find the difference of keys in the given dictionaries using Python. Example Input: dict1= {'key1':'Geeks', 'key2':'For', 'key3':'geeks'}, dict2= {'key1':'Geeks', 'key2':'Portal'} Output: key3 Explanation: key1 and key2 is already present
5 min read
Python | Combine the values of two dictionaries having same key
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Combining dictionaries is very common task in operations of dictionary. Let's see how to combine the values
7 min read
Python | Intersect two dictionaries through keys
Given two dictionaries, the task is to find the intersection of these two dictionaries through keys. Let's see different ways to do this task. Method #1: Using dict comprehension C/C++ Code # Python code to demonstrate # intersection of two dictionaries # using dict comprehension # initialising dictionary ini_dict1 = {'nikhil': 1, 'vashu' : 5, 'man
4 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
three90RightbarBannerImg