Hello Techies, In this tutorial we are going learn about how to compare two dictionaries.
Compare Two Dictionaries in Python
We will try to compare and see if both the dictionaries are same.
We will try to compare in 2 ways:
- Using == comparison operator
- Using deepdiff module
Using == comparison operator
# creating dictionaries dictionary_1 = { 'type': 'Dictionaries', 'name': 'Tutorial', } dictionary_2 = { 'type': 'Dictionaries', 'name': 'Tutorial', } if dictionary_1==dictionary_2: print("Both are same") else: print('Not same')
Output
Both are same
Explanation
- By using equality comparison operator we are checking if both are same or not.
- If comparison results True, we will print “Both are same”.
- If comparison results False, we will print “Not same”.
Using deepdiff module
# import libraries from deepdiff import DeepDiff # creating dictionaries dictionary_1 = { 'type': 'Dictionaries', 'name': 'Tutorial', } dictionary_2 = { 'type': 'Dictionaries', 'name': 'tutorial', 'problem':"Comparing dictionaries" } comparison = DeepDiff(dictionary_1,dictionary_2) print(comparison)
Output
{'dictionary_item_added': [root['problem']], 'values_changed': {"root['name']": {'new_value': 'tutorial', 'old_value': 'Tutorial'}}}
Explanation
- Basically deepdiff will give us difference of almost every python object.
- To get the difference we will pass the the dictionaries as parameters to the DeepDiff.
- If both are same it will print empty dictionary.
- Else it will print changes in any key values and any new items.
So to use this deepdiff module we have to install the library explicitly.
pip install deepdiff
If we want to use it in command line we can use this line:
pip install deepdiff[cli]
If we want to add some extra functionalities we can use this line
pip install deepdiff[optimize]
So that’s it for this article, stay tuned for more exciting information and updates