Hello Coders, I Hope you are doing well. In this blog post, We will learn to add Two Dictionaries in Python. Adding Dictionaries in Python is easy if you know the proper code or steps. We will discuss four different ways to add two dictionaries in python. Let us discuss these four ways in detail:-
1. Using Update Funcation:-
In this method, Firstly we will make two different dictionary named d1 and d2. After making these dictionary we will write the function update in the form d1.update(d2). Which will make the d2 dictionary combined with d1. Now d1 is updated and when we will print it. It will be merged dictionary.
update.py
OUTPUT
{‘name’ : ‘jatin’, ‘hobby’ : ‘writer’, ‘game’ : ‘badminton’, ‘fruit’ : ‘Mango’, ‘website’ : ‘Codeblockx’, ‘food’ : ‘Burger’}
2. Using Merge Funcation:-
In this Method, We will make two dictionary d1 and d2. After this we will make another dictionary d3 which will contain merger of d1 and d2. | symbol is used to merge the function. Now you can print d3 which will be merger or addition of d1 and d2 dictionaries.
merge.py
OUTPUT
{‘name’: ‘jatin’, ‘hobby’: ‘writer’, ‘game’: ‘badminton’, ‘fruit’ : ‘Mango’, ‘website’ : ‘Codeblockx’, ‘food’ : ‘Burger’}
3. Using Unpack Method:-
In this method, we will create two new dictionaries d1 and d2. We will use unpack method to add two dictionary. ** symbol is used to unpack the dictionary and combine it with other dictionary using , in the brackets. Now the dictionaries are combined.
unpack.py
OUTPUT
{‘name’: ‘jatin’, ‘hobby’: ‘writer’, ‘game’: ‘badminton’, ‘fruit’ : ‘Mango’, ‘website’ : ‘Codeblockx’, ‘food’ : ‘Burger’}
4. Using Def Method:-
This def function will be used with the help of update function. As we will define the update function in the def function to add or merge the dictionaries. We will name the def function as mergedic (a,b) and in place of a,b we will write the dictionary name which we want to add or merge.
def.py
OUTPUT
The merged dic is :
{‘name’: ‘jatin’, ‘hobby’: ‘writer’, ‘game’: ‘badminton’, ‘fruit’: ‘Mango’, ‘website’: ‘Codeblockx’, ‘food’: ‘Pizza’}
Hope this blog post was helpful to you and you have got the answer to your question. Thank you for visiting our blog. If you have any doubts about any coding questions then let us know in the comments section we will answer them as soon as possible. Till then check out our more blog posts.