In this tutorial, learn how to combine two dictionary variables in Python. The short answer is: use the two dictionary variables in comma separation and add a double asterisk (**). Read further to know the method and merge your dictionary.

The merging is the process of combining two dictionary elements in one. You can append one dictionary to the other. The second dictionary will be added to the end of the first. You may also like to read How to Delete Multiple Keys Items From Dictionary In Python.

How to combine two dictionary variables in Python

How to Combine Two Dictionary in Python

If you want to append the elements of the second dictionary after the elements of first. You can use the below-given method which put together the two dictionary elements.

To perform this task, you have to put two dictionary variable in comma separation. Also, add the double asterisk(**) to both the variables. After that enclose them within the curly brackets({}). Now, assign this to a new variable which gives the output as the combination of the dictionary variables.

Output

{‘one’: ‘Ram’, ‘two’: 13, ‘three’: ‘Jordge’, ‘four’: ‘Gill’, ‘five’: 33, ‘six’: ‘Steve’}

The above example showing the dictionary variable after merging. The merged variable contains 6 elements with each element contains the keys and its associated values.

Add More Items to Dictionary While Merging

Sometime, you may want to add more element while merging the two dictionaries. In that case, you have to just put the new elements as given in the example below. Each new element of the dictionary should contain keys with its associated values.

You can add the new items to the start, end and in between the two dictionaries. It depends upon you to put the new items to the required position in the dictionary.

Output

{‘one’: ‘Ram’, ‘two’: 13, ‘three’: ‘Jordge’, ‘seven’: ‘Billy’, ‘eight’: ‘Oman’, ‘four’: ‘Gill’, ‘five’: 33, ‘six’: ‘Steve’}

The above example showing the output contains the merged elements of two dictionaries. It also contains the elements which you want to add while merging.

You may also like to read

Hope, you like this post of how to merge two dictionaries in Python. If you have any query regarding the tutorial, please comment below.

Reference
Stackoverflow Discussion on Mergin of Dictionaries in Python

Also tell me, which method you are using to combine the dictionary.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.