2012-02-12 50 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