简体   繁体   中英

Comparing two dictionaries and printing key value pair in python

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.

As to the differences, You can use a dictionary comprehension to filter only b keys which are in a :

>>> {key: b[key] for key in b if key in a}
{'fruits': 'banana'}

To the second part, "if the keys have changed", {'froot'} isn't a valid dictionary, and keys are immutable. So it's not possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM