如何对dict元素求和 [英] How to sum dict elements

查看:33
本文介绍了如何对dict元素求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,我有字典列表:

In Python, I have list of dicts:

dict1 = [{'a':2, 'b':3},{'a':3, 'b':4}]

我想要一个包含所有字典总和的最终字典.即结果将是: {'a':5, 'b':7}

I want one final dict that will contain the sum of all dicts. I.e the result will be: {'a':5, 'b':7}

注意:列表中的每个字典都将包含相同数量的键值对.

N.B: every dict in the list will contain same number of key, value pairs.

推荐答案

有点丑,但单行:

dictf = reduce(lambda x, y: dict((k, v + y[k]) for k, v in x.iteritems()), dict1)

这篇关于如何对dict元素求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆