2013-02-19 43 views
0

我有很多類型的字典,我給2這個例子:更新或添加鍵類型的字典

dict1={'green': 3, 'yellow': 5, 'blue': 1} 
dict2={'green': 5, 'yellow': 1, 'blue': 3, 'purple': 10} 

我一直試圖找到一種方法來添加2種類型的字典所以我可以有更新的值(總和),併爲不存在的鍵添加鍵和值。

結果:

results = {'green': 8, 'yellow': 6, 'blue': 4, 'purple': 10} 

我試圖dict1.update(dict2)但你知道,我只帶了具有更新值的字典,而不是總結出來的。

任何方法來實現這一目標?

UPDATE:

解決:其實collections.Counter的伎倆...感謝

+0

使用collections.Counter。 – mgilson 2013-02-19 17:49:27

+0

你想爲重複鍵發生什麼?例如,你想'綠色'被映射到3,5,3 + 5或其他東西嗎? – 2013-02-19 17:50:19

+0

@KyleStrand:3 + 5,請參閱示例'results'字典。 – 2013-02-19 17:50:59

回答

0

咦,那是出奇的難...

dicts = [dict1, dict2] 
dict([(key, sum(map(lambda x: x.get(key) or 0, dicts))) for key in set(reduce(lambda a,b: a + b, map(lambda x: x.keys(), dicts), []))]) 

[{'blue':1,'green':3,'yellow':5},{'blue':3,'purple':10,'green':5,'yellow':1}]

或者更可讀

dicts = [dict1, dict2] 
keys = reduce(lambda a,b: a + b, map(lambda x: x.keys(), dicts), []) 
dict([(key, sum(map(lambda x: x.get(key) or 0, dicts))) for key in set(keys)]) 
0
{x: dict1.get(x,0) + dict2.get(x,0) for x in set(dict1.keys() + dict2.keys())} 

輸出:

{'blue': 4, 'purple': 10, 'green': 8, 'yellow': 6}