简体   繁体   English

比较2个词典中的键和值

[英]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! 麻烦和马车......需要帮助!

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. 也许这就是你所说的“and buggy”,因为他们正在检查一个字典中的值是另一个中的键。

This checks that the two dicts contain the same values for the same keys. 这将检查两个dicts是否包含相同键的相同值。 By constructing the union of the keys you can avoid looping twice, and then there are 4 cases to handle (instead of 8). 通过构造键的并集可以避免循环两次,然后有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

Sounds like using the features of a set might work. 听起来像使用一组功能可能会有用。 Similar to Ned Batchelder: 与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)

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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