Python:在一个列表中合并多个字典并更新值

Python:在一个列表中合并多个字典并更新值,python,dictionary,Python,Dictionary,以下是我的字典列表: dict_list=[{'red':3, 'orange':4}, {'blue':1, 'red':2}, {'brown':4, 'orange':7}, {'blue':4, 'pink':10}] 这是我的期望结果 [{'red':5, 'orange':11, 'blue':5, 'brown':4, 'pink':10}] 我尝试使用sum,但收到一条错误消息,更新似乎不适合这里 update_dict={} for x in dict_list:

以下是我的字典列表:

dict_list=[{'red':3, 'orange':4}, {'blue':1, 'red':2},
   {'brown':4, 'orange':7}, {'blue':4, 'pink':10}]
这是我的
期望结果

[{'red':5, 'orange':11, 'blue':5, 'brown':4, 'pink':10}]
我尝试使用sum,但收到一条错误消息,更新似乎不适合这里

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

有什么建议吗?谢谢。

defaultdict
是你的朋友

from collections import defaultdict

d = defaultdict(int)

for subdict in dict_list:
    for k,v in subdict.items():
        d[k] += int(v)
Python3语法。
int(v)
是必需的,因为您的字典中混合了字符串和int值

要获得所需的输出,请执行以下操作:

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}]
d
Out[16]:defaultdict(,{'orange':11,'blue':5,'pink':10,'red':5,'brown':4})
[主旨(d)]
Out[17]:[{'blue':5,'brown':4,'orange':11,'pink':10,'red':5}]

让我们通过将您的
dict_列表
转换为元组列表来简化这一点
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'}]

请张贴您的密码。谢谢您试图对
int
str
求和,这将出错。请确保您的dict格式正确。是否确实希望数字以字符串和数字的形式出现在
所需结果中?@roippi我很久以前写过这段代码。但请仔细查看他的预期输出。@thefourtheye我认为混合整数和字符串是错误的,例如红色的“3”+2=“5”。如果他真的想要一个包含一本字典的列表,那么好吧。嗨@roippi,谢谢你的解决方案。也许你想更新你的答案,使之成为一个字典列表。非常感谢@roippi,我很感激。