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.

Answers


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.


Need Your Help

Is this bad coupling?

java

I'm attempting to solve a path planning problem in 3D space and have succeeded, but I don't know if my solution has adequately loose coupling. I have three source files, each containing a public cl...

Declaration of Issue after upgrading cakephp 1.3 to 2.0

cakephp upgrade

I am getting this issue when I try to upgrade from cakephp 1.3 to 2.0

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.