2015-12-08 102 views
0

我有2個字典的int值作爲鍵。我想從鍵字相同的字典中減去這些值。比較2字典和減去鍵

例子:

dictA={'key1':3, 'key2':4, 'key3':9, 'key5':5} 
dictB={'key1':2, 'key2':5, 'key3':5, 'key4':4} 

輸出我想要的東西:

difference = {'key1':1,'key2':1,'key3':4,'key4':4,'key5':5} 

回答

2
>>> dictA={'key1':3, 'key2':4, 'key3':9, 'key5':5} 
>>> dictB={'key1':2, 'key2':5, 'key3':5, 'key4':4} 
>>> dict((k, abs(dictA.get(k, 0) - dictB.get(k, 0))) for k in set(dictA.keys())|set(dictB.keys())) 
{'key3': 4, 'key2': 1, 'key1': 1, 'key5': 5, 'key4': 4} 
>>> _ == {'key1':1,'key2':1,'key3':4,'key4':4,'key5':5} 
True 

沒錯的要求。經過Python 2.7.3測試。

+0

太棒了,非常感謝你^^。 – Jayyzz