-->

Merging two Dictionaries- Python

By: Priya Philip 4 months, 1 week ago

There are various ways in python to merge Dictionaries. Few of them are shown below.

  1. By using update()
    By using 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:
    
    # Python code to merge dict using update() method
    dict1 = {'a': 20, 'b': 6}
    dict2 = {'d': 5, 'c': 9}
    d = dict2.update(dict1)
    
    print(d) #returns none
    
    print dict2
    

    Output:

    None
    {'a': 20, 'c': 9, 'b': 6, 'd': 5}
    
  2. By using **
    In Python 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 the 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:
    # Python code to merge dict using a single expression
    dict1 = {'a': 10, 'b': 8} 
    dict2 = {'d': 6, 'c': 4} 
    res = {**dict1, **dict2}
    print(res) 
    

    Output:

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

Comments

Let us talk!

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.