Merge dictionaries without duplicates in Python

Here in this tutorial, we will learn how to merge Dictionaries without duplicates in Python.

Merge Dictionary without duplication

Here, we need to first understand the Dictionary in Python.

  • A dictionary is mutable data which means we add or remove data. The Dictionaries are ordered, mutable not allow duplication of data.
    sample_dictionary = {"Name":"John",
                         "email":"[email protected]",

Here you can create a dictionary with input data in the form of key-value pairs because Merging two dictionaries together, or concatenating different dictionaries or the same dictionaries without duplicates in Python and there are no duplicates of the same key.

First, create a dictionary from the same or possibly different key pairs. Various ways to merge dictionaries without duplicates in Python.

By using update() Method :

Here you can merge two different dictionaries into one dictionary without duplication because it Uses this to overwrite the first dictionary with another, call it merge. e.g,

               # Merge dictionaries without duplicates in Python
dict_1 = {"Name":"John","Age":32,"Location":"France"}
dict_2 = {"Name" :"Liton","Office_Location":"Germany","Profession":"Employee"}          

print("The Merged Dictionary is : " ,dict_1)

Output_1 :-

The Merged Dictionary is : {'Name': 'Liton', 'Age': 32, 'Location': 'France', 
'Office_Location': 'Germany', 'Profession': 'Employee'}

By using Merge(|) Operator : Also known as pipe character

Now you can use this operator (|) to merge the two dictionaries. This merges two different dictionaries without duplicate keys and values.

                # Merge dictionaries without duplicates in Python
def Merge(dict_1, dict_2):
  result = dict_1 | dict_2
  return result

dict_1 = {"Name":"John","Age":32,"Location":"France"}
dict_2 = {"Name" :"Liton","Profession":"Employee"}          

Merged_dict = Merge(dict_1, dict_2)
print("The Merged Dictonary is : ",Merged_dict)

Output_2 :-

The Merged Dictionary is: {'Name': 'Liton', 'Age': 32, 
'Location': 'France', 'Profession': 'Employee'}

Using the unpacking of the second dictionary:

                  #  Merge dictionaries without duplicates in Python
dict_1= {'John_wick': 150, 'Rick_Johnson': 106, 'Misa_jerky' : 123 }
dict_2= {'Bonnie_Lavi': 189,'Rick': 205,'Matt_luo' : 164 }


Output_3 :-

{'John_wick': 150, 'Rick': 205, 'Misa_jerky': 123, 'Bonnie_Lavi': 189, 'Matt_luo': 164}

Basically, these three different methods are used to merge the different dictionaries because it also used for merging the dictionaries without duplicates in Python.


For more information, use the link below to learn about the built-in Python dictionary.

Leave a Reply

Your email address will not be published. Required fields are marked *