Chris Lin Chris Lin - 1 month ago 11
Python Question

Comparing two dictionaries Key values and return a new dictionary with the differences - Python

What I want to do is to compare two dictionaries:

predict = {'eggs': [1,2],'ham': [1,2,3]}
actual = {'eggs': [2], 'ham': [1,2]}


and return a new dictionary of the difference:

difference = {'eggs': [1],'ham': [3]}


What would be an efficient way to do this? Thanks.

Answer Source

You can combine set.difference() and dict comprehension:

>>> predict = {'eggs': [1,2],'ham': [1,2,3]}
>>> actual = {'eggs': [2], 'ham': [1,2]}
>>> difference = {k: list(set(v).difference(actual[k])) for k, v in predict.items()}
{'eggs': [1], 'ham': [3]}

Explanation:

  • You iterate over predict key-value pairs
  • The new difference dictionary will have the same keys as predict and actual
  • But its values will be the set difference of the current lists
  • set(v).difference(actual[k]) - As the keys are the same, you can access actual[k] and find its difference with the current one (which is v)
  • Finally, you cast your result set with the difference to a list to have an output as requested.