我想获取一个字典中填充的聚合数字,并将键和值与另一个字典中的键和值进行比较,以确定两者之间的差异。我只能得出如下结论:
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'
麻烦而且有问题...需要帮助!
最佳答案
我不确定你的第二对循环试图做什么。也许这就是您所说的“和 buggy ”的意思,因为他们正在检查一个字典中的值是否是另一个字典中的键。
这会检查两个字典是否包含相同键的相同值。通过构造键的并集,您可以避免循环两次,然后有 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
关于python - 比较 2 个字典中的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9253493/