close

How to get the difference between two dictionaries in Python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get the difference between two dictionaries in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to get the difference between two dictionaries in Python?

  1. How to get the difference between two dictionaries in Python?

    Try the following snippet, using a dictionary comprehension:
    value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }

  2. get the difference between two dictionaries in Python

    Try the following snippet, using a dictionary comprehension:
    value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }

Method 1

Try the following snippet, using a dictionary comprehension:

value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }

In the above code we find the difference of the keys and then rebuild a dict taking the corresponding values.

Method 2

Another solution would be dictdiffer 

import dictdiffer                                          

a_dict = {                                                 
  'a': 'foo',
  'b': 'bar',
  'd': 'barfoo'
}                                                          

b_dict = {                                                 
  'a': 'foo',                                              
  'b': 'BAR',
  'c': 'foobar'
}                                                          

for diff in list(dictdiffer.diff(a_dict, b_dict)):         
    print diff

A diff is a tuple with the type of change, the changed value, and the path to the entry.

('change', 'b', ('bar', 'BAR'))
('add', '', [('c', 'foobar')])
('remove', '', [('d', 'barfoo')])

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read