0

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.

user3349548
  • 43
  • 1
  • 1
  • 5

2 Answers2

3

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
1

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.

mhlester
  • 22,781
  • 10
  • 52
  • 75