如何对分配给字典列表中的键的值求和? [英] How to sum the values assigned to a key in a list of dictionaries?

查看:82
本文介绍了如何对分配给字典列表中的键的值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字典清单如下:

A=[
    {key1 : val11, key2 : val21, key3 : val31, key5 : val51, key6 : val61},
    {key2 : val22, key3 : val32, key5 : val52, key6 : val62},
    {key1 : val13, key2 : val23, key4 : val43, key5 : val53},
    {key1 : val14, key3 : val34, key4 : val44, key5 : val54, key6 : val64},
    {key4 : val45, key5 : val55, key6 : val65}
]

如您所见,字典的长度并不相同,每个字典中的key : value也不一定相似.我想知道如何对所有字典中为每个键分配的值求和:

As you see the length of the dictionaries are not the same and also the key : value in each dictionary are not necessarily similar. I was wondering how to sum the values assigned for each key in all dictionaries:

例如对于key4: (val43 + val44 + val45)key3: (val31 + val32 + val34).

推荐答案

从此开始-

A = [{1 : 5, 2  : 3, 3 : 4}, {1 : 1, 5: 10, 3: 2}, {100 : 2}]

这是使用 数据结构-

  1. 使用map
  2. 将每个字典转换为Counter
  3. 将每个Counter对象与sum
  4. 相加
  1. Convert each dict to a Counter using map
  2. Sum each Counter object with sum

from collections import Counter
r = sum(map(Counter, A), Counter())

r
Counter({1: 6, 2: 3, 3: 6, 5: 10, 100: 2})

关于Counter的伟大之处在于,您可以将它们很好地相加. sum的第二个参数是"sum"的开头.如果要返回字典(而不是Counter),请调用dict(r).

The great thing about Counters is that you can add them up, quite nicely. The second argument to sum is the start of the "sum". If you want a dictionary back (instead of a Counter), call dict(r).

请注意,当您的字典只有具有数字值的键时,此解决方案才有效.

Note that this solution works when your dicts only have keys with numeric values.

这篇关于如何对分配给字典列表中的键的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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