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


what want compare 2 dictionaries:

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

and return new dictionary of difference:

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

what efficient way (for large amount of data) this? thanks.

you can combine set.difference() , dict comprehension:

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

explanation:

  • you iterate on predict key-value pairs
  • the new difference dictionary have same keys predict , actual
  • but values set difference of current lists
  • set(v).difference(actual[k]) - keys same, can access actual[k] , find difference current 1 (which v)
  • finally, cast result set difference list have output requested.

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -