比较两个字典中的键和值

3

我希望将一个字典中填充的汇总数字与另一个字典中的键和值进行比较,以确定两者之间的差异。 我只能得出以下结论:

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'

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


这两个字典是否具有相同的键集? - Joel Cornett
你可以使用 res1 == res2 来比较字典,但你是否还需要找出哪些部分不同呢? - Greg Hewgill
dict.keys是一个无用的函数,a.keys() == list(a),而且显式地列出键名也很少有用。 - Jochen Ritzel
字典具有不同的键集(一些匹配)以及不同的值(一些匹配)。 - NewToPy
@JochenRitzel:dict.keys() 的含义比 list(dict) 更明确。 - jsbueno
我认为你需要准确解释一下“比较值”的含义。最好给出一些输入和输出的示例。现在这样说,我觉得没有人真正理解你在问什么。 - Laurence Gonsalves
3个回答

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

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)

我正在比较键和值的差异,所以我决定采纳您的建议并改用iteritems,如下所示:available=set(fruit_available.iteritems()) satchel=set(my_satchel.iteritems()) print available.difference(satchel), satchel.difference(available) - NewToPy
请注意,set(fruit_available.keys())与set(fruit_available)等效(并且可能更清晰)。 - Gregory Kuhn

1

我不完全确定您所说的匹配键和值是什么意思,但这是最简单的方法:

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

在Python 2.7中使用a.viewkeys() - b.viewkeys(),在Python 3.x中使用a.keys() - b.keys() - Sven Marnach
这样做是可行的,但无法区分不同的键值对。也许可以使用键值元组集合? - Joel Cornett
这些字典有不同的键集,这仍然有效吗? - NewToPy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接