如何总结dict元素 [英] How to sum dict elements

查看:104
本文介绍了如何总结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}

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

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

推荐答案

有点丑陋,但是一个对于k,-liner:

A little ugly, but a one-liner:

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

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

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