在两个字典中比较键和值

3 投票
3 回答
13499 浏览
提问于 2025-04-17 12:55

我想把一个字典里的所有数字汇总起来,然后把这个字典的键(也就是名字)和对应的值(也就是数字)跟另一个字典的键和值进行比较,看看这两个字典之间有什么不同。我目前只能得出一些像下面这样的结论:

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 个回答

1

我不太明白你说的“匹配键和值”是什么意思,不过这是最简单的例子:

a_not_b_keys = set(a.keys()) - set(b.keys())
a_not_b_values = set(a.values()) - set(b.values())
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

我不太明白你第二组循环想要做什么。也许这就是你所说的“有问题”的原因,因为它们在检查一个字典中的值是否是另一个字典的键。

这个检查是为了确认两个字典在相同的键下是否有相同的值。通过构建键的并集,你可以避免循环两次,这样就只需要处理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

撰写回答