比较2个词典中的键和值

时间:2012-02-12 22:55:30

标签: python

我想取一个字典中填充的聚合数字,并将键和值与另一个字典中的键和值进行比较,以确定两者之间的差异。我只能得出如下结论:

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'

笨重而且错误......需要帮助!

3 个答案:

答案 0 :(得分:2)

我不确定你的第二对循环试图做什么。也许这就是你所说的“and buggy”,因为他们检查一个字典中的值是另一个中的键。

这将检查两个dicts是否包含相同键的相同值。通过构造键的并集可以避免循环两次,然后有4种情况需要处理(而不是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

答案 1 :(得分:2)

听起来像使用一组功能可能会有效。与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)

答案 2 :(得分:1)

我不完全确定你的意思是匹配键和值,但这是最简单的:

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