I have two dictionaries:
a= { "fruits": ["apple", "banana"] }
b = { "fruits": ["apple", "carrot"]}
Now I want to print the differences. And I want to
In this case the output should be
{'fruits' : 'carrot'}
also if the keys have changed - suppose if has changed to
b = { "toy": "car"}
then the output should be
{ "toy": "car"}
Thanks in advance.
解决方案
It seems like dict.viewitems might be a good method to look at. This will allow us to easily see which key/value pairs are in a that aren't in b:
>>> a = { 'fruits': 'apple' 'grape', 'vegetables': 'carrot'}
>>> b = { 'fruits': 'banana'}
>>> a.viewitems() - b.viewitems() # python3.x -- Just use `items` :)
set([('fruits', 'applegrape'), ('vegetables', 'carrot')])
>>> b['vegetables'] = 'carrot' # add the correct vegetable to `b` and try again.
>>> a.viewitems() - b.viewitems()
set([('fruits', 'applegrape')])
We can even get a handle on what the difference actually is if we use the symmetric difference:
>>> a.viewitems() ^ b.viewitems()
set([('fruits', 'applegrape'), ('fruits', 'banana')])
You could also do something similar with viewkeys (keys on python3.x) if you're only interested in which keys changed.