2012-02-12 44 views
3

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

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' 

笨重和越野车......需要帮助!

+0

两个词典都有相同的一组键吗? – 2012-02-12 23:00:05

+0

你可以用'res1 == res2'来比较dictonaries,你还需要找出哪些*部分不同? – 2012-02-12 23:06:15

+0

'dict.keys'是一个无用的函数,'a.keys()== list(a)'和一个显式的键列表几乎不会有用。 – 2012-02-12 23:50:53

回答

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 
1

我不完全相信你通过匹配键和值是什么意思,但是这是最简单的:

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

或Python 2.7中的'a.viewkeys() - b.viewkeys()',Python 3.x中的'a.keys() - b.keys()'。 – 2012-02-12 23:11:18

+0

这将工作,但不会歧视不同的密钥配对。也许做一个关键,价值元组设置? – 2012-02-12 23:37:32

+0

词典有不同的键集,这仍然有效吗? – NewToPy 2012-02-12 23:55:24

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) 
+0

容易多了!非常感谢! – NewToPy 2012-02-15 03:55:14

+0

我比较键和值的差异,所以我决定采取你的建议,并修改以利用iteritems,如下所示:'available = set(fruit_available.iteritems())''satchel = set(my_satchel.iteritems()) 'print print.difference(satchel),satchel.difference(available)' – NewToPy 2012-02-15 17:07:36

+0

注意set(fruit_available.keys())与set(fruit_available)是等价的(也许更清晰) – 2015-07-30 14:38:35