NewToPy
NewToPy

Reputation: 67

Comparing Keys and Values in 2 Dictionaries

I want to take the aggregate numbers populated in one dictionary and compare both the keys and the values against keys and values in another dictionary to determine differences between the two. I can only conclude something like the following:

for i in res.keys():

    if res2.get(i):
        print 'match',i
    else:
        print i,'does not match'

for i in res2.keys():

    if res.get(i):
        print 'match',i
    else:
        print i,'does not match'

for i in res.values():

    if res2.get(i):
        print 'match',i
    else:
        print i,'does not match'

for i in res2.values():

    if res.get(i):
        print 'match',i
    else:
        print i,'does not match'

cumbersome and buggy...need help!

Upvotes: 3

Views: 13518

Answers (3)

tbc
tbc

Reputation: 1749

Sounds like using the features of a set might work. Similar to Ned Batchelder:

fruit_available = {'apples': 25, 'oranges': 0, 'mango': 12, 'pineapple': 0 }

my_satchel = {'apples': 1, 'oranges': 0, 'kiwi': 13 }

available = set(fruit_available.keys())
satchel = set(my_satchel.keys())

# fruit not in your satchel, but that is available
print available.difference(satchel)

Upvotes: 2

Ned Batchelder
Ned Batchelder

Reputation: 376052

I'm not entirely sure what you mean by matching keys and values, but this is the simplest:

a_not_b_keys = set(a.keys()) - set(b.keys())
a_not_b_values = set(a.values()) - set(b.values())

Upvotes: 1

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143344

I'm not sure what your second pair of loops is trying to do. Perhaps this is what you meant by "and buggy", because they're checking that the values in one dict are the keys in the other.

This checks that the two dicts contain the same values for the same keys. By constructing the union of the keys you can avoid looping twice, and then there are 4 cases to handle (instead of 8).

for key in set(res.keys()).union(res2.keys()):
  if key not in res:
    print "res doesn't contain", key
  elif key not in res2:
    print "res2 doesn't contain", key
  elif res[key] == res2[key]:
    print "match", key
  else:
    print "don't match", key

Upvotes: 2

Related Questions