2016-04-21 69 views
1

在字典中的這個列表總結價值觀,我想總結一下匹配的密鑰的values,使輸出如下所示:如何合併類型的字典列表,重複鍵

dict_x = [{(1, 2): 100}, {(1, 3): 150}, {(1, 3): 150, (3, 4): 150}, {(4, 5): 10, (1, 3): 10, (3, 4): 10}, {(5, 6): 15}] 

output:{(1, 2): 100, (1, 3): 310, (3, 4): 160, (4, 5): 10, (5, 6): 15} 

我有通過諸如How can I count the occurrences of a list item in Python?Count how many times a part of a key appears in a dictionary python之類的頁面進行瀏覽時,它們會計算匹配元素的出現次數,但它們不會完全匹配匹配元素的總和。感謝您的時間。

+0

dict_x的定義是行不通的:它是一個字典列表,但最後一個元素 - ((5,6):15')不是字典。最終的元素應該是「{(5,6):15}」嗎? –

+0

@JamesBuerger是 – Nobi

回答

2

這裏是一種與collections.Counter做一通:

>>> from collections import Counter 
>>> sum(map(Counter, dict_x), Counter()) 
Counter({(1, 2): 100, (1, 3): 310, (3, 4): 160, (4, 5): 10, (5, 6): 15}) 

上回應:

也許不是最有效的方式,但對於小的單子,你可以做這兩次通過:

>>> keys = [k for d in dict_x for k in d] 
>>> {k: sum(d.get(k, 0) for d in dict_x) for k in keys} 
{(1, 2): 100, (1, 3): 310, (3, 4): 160, (4, 5): 10, (5, 6): 15} 

第一行獲取所有鍵,第二行彙總結果。我幾乎肯定有一些更聰明的方式來使用python buildins來做到這一點...我會考慮它。

+0

謝謝。特別是對於高效版本,因爲它將用於更大的列表 – Nobi

+0

我非常喜歡Counter解決方案!人們可以對計數器使用算術,而且很多人忽略了這一點。 – ursan

1
out_dict = {} 
for a in dict_x: 
     for b in a.keys(): 
       out_dict[b] = out_dict.get(b, 0) + a[b] 

print out_dict 
+1

我會在a.iteritems()中使用'for b,v:'並避免額外查找'a [b]'。 –

0

這裏是一個可能的解決方案(foo就可以進一步優化):

dict_x = [{(1, 2): 100}, {(1, 3): 150}, {(1, 3): 150, (3, 4): 150}, {(4, 5): 10, (1, 3): 10, (3, 4): 10}, {(5, 6): 15}] 
new_dict_x = {} 

def foo(x): 
    global new_dict_x 
    for item in x.keys(): 
     new_dict_x[item] = new_dict_x.get(item, 0) + x[item] 

list(map(lambda x: foo(x),dict_x)) 

print('Input: {}'.format(dict_x)) 
print('Output: {}'.format(new_dict_x)) 

輸出:

Input: [{(1, 2): 100}, {(1, 3): 150}, {(1, 3): 150, (3, 4): 150}, {(4, 5): 10, (1, 3): 10, (3, 4): 10}, {(5, 6): 15}] 
Output: {(1, 2): 100, (4, 5): 10, (5, 6): 15, (1, 3): 310, (3, 4): 160} 
相關問題