2017-05-10 22 views
0

我有:途徑字典的鍵和值比較在python

dictionary1 = {'Zookeeper': 3, 'Profit': 3, 'Collector': 3, 'Service': 3} 

dictionary2 = {'Zookeeper': 2, 'Profit': 2} 

dictionary2可以是或可以不是相同的長度,並且可以或可以不具有與相同的值dictionary1。如何編寫Python函數來比較這些字典並打印dictionary2中與dictionary1不匹配的值的密鑰?

我來到了這個只有匹配的鑰匙:

check_result = set(dictionary1.keys()) == set(dictionary2.keys()) 

但我需要的東西更加精確。

+0

參照第一條答案http://stackoverflow.com/questions/9253493/比較鍵和值在2字典 – Jointts

+0

我想我已經理解你的問題,檢查答案並驗證!享受!乾杯。 –

回答

1

終於我明白你的問題,這應該做的工作:

dictioanry1 = {'Zookeeper': 3, 'Profit': 3, 'Collector': 3, 'Service': 3} 
dictionary2 = {'Zookeeper': 2, 'Profit': 2} 

A = list(dictioanry1.keys()) 
B = list(dictionary2.keys()) 
commonKeys = set(A) - (set(A) - set(B)) 


for key in commonKeys: 
    if(dictioanry1[key] != dictionary2[key]): 
     print (key + ":" + str(dictionary2[key]) + " should be " + str(dictioanry1[key])) 

    $ Profit:2 should be 3 
    $ Zookeeper:2 should be 3 

commonKeys是匹配的密鑰,好嗎?和A是dictionary1.keys()(我把它們放到兩個變量中,以便更加克萊爾),所以,我想打印dictionary2(或B)中的所有值,但不匹配,所以,你問是否不屬於匹配列表

+0

達米安,謝謝你的答案,我可以得到鑰匙,但我需要那些與dictionary1中不匹配的dictionary2中的元素的鍵和值。假設dictionary2有'Zookeeper':2,'Profit':2但是在dictionary1中這些值是'Zookeeper':3,'Profit':3.所以我想打印像Zookeeper有2點但是應該有3和Profit有2積分但應該有3 – Rob

+0

完美,我爲你更新了答案 –

+0

非常好。感謝達米安的幫助。這給我想要的確切結果.. – Rob

0

我正在解決類似的問題,並使用了一個可以在此適用的解決方案。

如果你想打印從dictionary2不與dictionary1你可以嘗試這樣的

>>> dictionary1 = {'Zookeeper': 3, 'Profit': 3, 'Collector': 3, 'Service': 3} 
>>> dictionary2 = {'Zookeeper': 2, 'Profit': 2} 
>>> [ key for key, val in dictionary2.items() if dictionary1.get(key, None) != val ] 
['Zookeeper', 'Profit'] 

從dictionary2不與dictionary1的匹配值僅返回鍵東西值相匹配的鑰匙你問的問題。我發現它更有益,於我而言,來回報不匹配的字典中的鍵和值:

>>> dictionary1 = {'Zookeeper': 3, 'Profit': 3, 'Collector': 3, 'Service': 3} 
>>> dictionary2 = {'Zookeeper': 2, 'Profit': 2} 
>>> { key: val for key, val in dictionary2.items() if dictionary1.get(key, None) != val } 
{'Zookeeper': 2, 'Profit': 2}