2013-10-12 136 views
1

这里的更新是我的字典的名单:的Python:在列表中合并多个字典与价值观

dict_list=[{'red':3, 'orange':4}, {'blue':1, 'red':2}, 
    {'brown':4, 'orange':7}, {'blue':4, 'pink':10}] 

这里是我的desired outcome

[{'red':5, 'orange':11, 'blue':5, 'brown':4, 'pink':10}] 

我已经使用和尝试,但得到一个错误信息,更新似乎并不适合。

update_dict={} 
for x in dict_list: 
    for a in x.items(): 
     update_dict+= x[a] 

有什么建议吗?谢谢。

+1

请张贴您的代码。谢谢! –

+0

你正在尝试总结'int'和'str',这会出错。确保您的字典格式正确。 – zeantsoi

+0

你真的确定你想要的字符串和数字中的数字,如你想要的结果吗? – thefourtheye

回答

2

defaultdict是你的朋友。

from collections import defaultdict 

d = defaultdict(int) 

for subdict in dict_list: 
    for k,v in subdict.items(): 
     d[k] += int(v) 

Python 3语法。 int(v)是必要的,因为您在字典中混合了字符串和整型值。

要获得您想要的输出:

d 
Out[16]: defaultdict(<class 'int'>, {'orange': 11, 'blue': 5, 'pink': 10, 'red': 5, 'brown': 4}) 

[dict(d)] 
Out[17]: [{'blue': 5, 'brown': 4, 'orange': 11, 'pink': 10, 'red': 5}] 
+0

嘎,你打我 – TerryA

+1

@roippi我在一段时间后写了这段代码。但仔细看看他的预期产出。 – thefourtheye

+0

@thefourtheye我认为混合整数和字符串是一个错误,例如'3'+ 2 ='5'代表'red'。如果他真的想要一个带有单个字典的列表,那好吧。 – roippi

0

让我们简化此通过转换了一下你的dict_list成元组的列表。 itertools.chain擅长这类事情。

from itertools import chain 

dict_list=[{'red':'3', 'orange':4}, {'blue':'1', 'red':2}, 
    {'brown':'4', 'orange':7}, {'blue':'4', 'pink':10}] 

def dict_sum_maintain_types(dl): 
    pairs = list(chain.from_iterable(i.items() for i in dl)) 

    # Initialize the result dict. 
    result = dict.fromkeys(chain(*dl), 0) 

    # Sum the values as integers. 
    for k, v in pairs: 
    result[k] += int(v) 

    # Use the type of the original values as a function to cast the new values 
    # back to their original type. 
    return [dict((k, type(dict(pairs)[k])(v)) for k, v in result.items())] 

>>> dict_sum_maintain_types(dict_list) 
[{'orange': 11, 'blue': '5', 'pink': 10, 'red': 5, 'brown': '4'}] 
相关问题