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'}]