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
predictkey-value pairs - the new
differencedictionary have same keyspredict,actual - but values
set differenceof current lists set(v).difference(actual[k])- keys same, can accessactual[k], find difference current 1 (whichv)- finally, cast result set difference list have output requested.
Comments
Post a Comment