How to Merge Dictionaries in Python with Keys and Values

Spread the love

In this tutorial, you will learn about How to merge dictionaries in python with keys and values.

First we need to create 2 dictionaries then, we have update first dictionary with secondary dictionary.

Merge Two Dictionaries with Values :

old_employes = {'ravi':1, 'raju': 2} new_employes = {'rakesh':10, 'david': 11} old_employes.update(new_employes) print(old_employes)

Output:

{'ravi': 1, 'raju': 2, 'rakesh': 10, 'david': 11}

Merge Two Dictionaries with keys: 

We can same keys, But if we merge like that the old key value is updated with new value.

old_employes = {'ravi':1, 'rakesh': 2} new_employes = {'rakesh':10, 'david': 11} old_employes.update(new_employes) print(old_employes)

Output:

{'ravi': 1, 'rakesh': 10, 'david': 11}

Merge Two Dictionaries on single expression: 

old_employes = {'ravi':1, 'rakesh': 2} new_employes = {'rakesh':10, 'david': 11} employees={**old_employes,**new_employes} print(employees)

Output:

{'ravi': 1, 'rakesh': 10, 'david': 11}

 

 

admin

admin

Leave a Reply

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