比较两个字典中的键和值

2024-01-11

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

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'

麻烦且有问题......需要帮助!


我不确定你的第二对循环想要做什么。也许这就是您所说的“和错误”的意思,因为他们正在检查一个字典中的值是否是另一个字典中的键。

这会检查两个字典是否包含相同键的相同值。通过构造键的并集,您可以避免循环两次,然后有 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

比较两个字典中的键和值 的相关文章

随机推荐