简体   繁体   English

字典值的总和列表

[英]sum list of dictionary values

I have a list of dictionary in this form : 我有一个这种形式的字典列表:

[
{'signal_8': 1, 'signal_1': 7, 'signal_10': 5, 'signal_5': 2, 'signal_2': 5, 'signal_6': 3, 'signal_4': 9, 'signal_3': 6, 'signal_9': 4, 'signal_7': 8}, 

{'signal_8': 1, 'signal_1': 7, 'signal_10': 5, 'signal_5': 2, 'signal_2': 5, 'signal_6': 3, 'signal_4': 9, 'signal_3': 6, 'signal_9': 4, 'signal_7': 8},

{'signal_8': 1, 'signal_1': 7, 'signal_10': 5, 'signal_5': 2, 'signal_2': 5, 'signal_6': 3, 'signal_4': 9, 'signal_3': 6, 'signal_9': 4, 'signal_7': 8},
]

and I want to sum the values in this by key for each element in the list like that : 并且我希望将列表中每个元素的键值相加:

    {
     'signal_8': 3,
     'signal_1': 21,
     'signal_10': 15,
     'signal_5': 6,
     'signal_2': 15,
     'signal_6': 9,
     'signal_4': 27,
     'signal_3': 18,
     'signal_9': 12,
     'signal_7': 24
    }

what I have tried is the following : 我试过的是以下内容:

    result = {}
    sm = 0
    for elm in original_list:
        for k,v in elm.items():
            sm += v
            result[k] = sm
    print(result)

but it still doesn't work. 但它仍然无效。

Similar to daveruinseverything's answer, I'd solve this with a Counter , but make use of its update method. 与daveruinseverything的答案类似,我用Counter解决了这个问题,但是使用了它的update方法。

Let signals be your list of dicts. signals成为您的词典列表。

>>> from collections import Counter
>>> c = Counter()
>>> for d in signals:
...     c.update(d)
... 
>>> c
Counter({'signal_4': 27, 'signal_7': 24, 'signal_1': 21, 'signal_3': 18, 'signal_10': 15, 'signal_2': 15, 'signal_9': 12, 'signal_6': 9, 'signal_5': 6, 'signal_8': 3})

For Op's sake, can you briefly describe what's happening here? 为了Op,你能简单描述一下这里发生了什么吗?

A Counter works similar to a dict , but its update method adds values to the values of pre-existing keys instead of overriding them. Counter工作方式与dict类似,但其update方法会将值添加到预先存在的键的值中,而不是覆盖它们。

What you want is the Counter collection type. 你想要的是Counter集合类型。 The Python docs on collections describe it best, but essentially a Counter is a special kind of dictionary where all the values are integers. 集合上的Python文档最好地描述它,但本质上Counter是一种特殊的字典,其中所有值都是整数。 You can pass any key, including nonexistent ones, and add to them. 您可以传递任何密钥,包括不存在的密钥,并添加到它们。 For example: 例如:

from collections import Counter

original_list = [
    {'signal_8': 1, 'signal_1': 7, 'signal_10': 5, 'signal_5': 2, 'signal_2': 5, 'signal_6': 3, 'signal_4': 9, 'signal_3': 6, 'signal_9': 4, 'signal_7': 8}, 
    {'signal_8': 1, 'signal_1': 7, 'signal_10': 5, 'signal_5': 2, 'signal_2': 5, 'signal_6': 3, 'signal_4': 9, 'signal_3': 6, 'signal_9': 4, 'signal_7': 8},
    {'signal_8': 1, 'signal_1': 7, 'signal_10': 5, 'signal_5': 2, 'signal_2': 5, 'signal_6': 3, 'signal_4': 9, 'signal_3': 6, 'signal_9': 4, 'signal_7': 8},
]

result = Counter()

for elem in original_list:
    for key, value in elem.items():
        result[key] += value

print(result)

Edit: @timgeb provides a variation on this answer which makes native use of the update() method on Counter objects. 编辑:@timgeb提供了这个答案的变体,它使Counter对象的本地使用update()方法。 I would recommend that as the best answer here 我建议这里作为最好的答案

The problem with your code is that you are summing sm and v no matter the key. 您的代码的问题在于,无论密钥是什么,您都要汇总smv Below you can find a reformatted version of your code that works. 您可以在下面找到适用于您的代码的重新格式化版本。 It simply adds the values from each element from the list to the result object: 它只是将列表中每个元素的值添加到结果对象:

from collections import defaultdict

result = defaultdict(int)

for elm in original_list:
    for k, v in elm.items():
        result[k] += v
print(result)

Or, with a one liner you can have: 或者,只需一个衬垫,您就可以:

result = {key: sum(e[key] for e in original_list) for key in original_list[0].keys()}

With itertools.groupby , you could do something like 使用itertools.groupby ,你可以做类似的事情

merged_list = sorted(p for l in original_list for p in l.items())
groups = groupby(merged_list, key=lambda p: p[0])
result = {signal: sum(pair[1] for pair in pairs) for signal, pairs in groups}

If you can assume that each dictionary contains the exact same keys, the above can be simplified to 如果您可以假设每个字典包含完全相同的键,则上面的内容可以简化为

{k: sum(d[k] for d in original_list) for k in original_list[0]}

Note also that the data analysis library pandas makes operations such as these trivial: 另请注意,数据分析库pandas使这些操作变得微不足道:

In [70]: import pandas as pd

In [72]: pd.DataFrame(original_list).sum()
Out[72]:
signal_1     21
signal_10    15
signal_2     15
signal_3     18
signal_4     27
signal_5      6
signal_6      9
signal_7     24
signal_8      3
signal_9     12
dtype: int64

Your current code uses one accumulating sum for all the signals, when instead you need a seperate the sum for each signal. 您当前的代码对所有信号使用一个累加和,而您需要为每个信号分别求和。

If you want your original code to work, you need to first check if the key exists in result , and initialise it 0 beforehand if it isn't. 如果你希望你的原始代码工作,你需要首先检查钥匙存在的result ,并初始化它事先0,如果事实并非如此。 Then accumulate the sum for the respective key. 然后累积相应密钥的总和。

Code: 码:

result = {}
for elm in original_list:
    for k, v in elm.items():

        # Initialise it if it doesn't exist
        if k not in result:
            result[k] = 0

        # accumulate sum seperately 
        result[k] += v

print(result)

Output: 输出:

{'signal_9': 12, 'signal_8': 3, 'signal_1': 21, 'signal_3': 18, 'signal_2': 15, 'signal_5': 6, 'signal_4': 27, 'signal_7': 24, 'signal_6': 9, 'signal_10': 15}

Note: As others have shown, to avoid initialising yourself, you can use collections.defaultdict() or collections.Counter() instead. 注意:正如其他人所示,为避免自己初始化,您可以使用collections.defaultdict()collections.Counter()代替。

Try this: 尝试这个:

original_list = [
{'signal_8': 1, 'signal_1': 7, 'signal_10': 5, 'signal_5': 2, 'signal_2': 5, 'signal_6': 3, 'signal_4': 9, 'signal_3': 6, 'signal_9': 4, 'signal_7': 8}, 

{'signal_8': 1, 'signal_1': 7, 'signal_10': 5, 'signal_5': 2, 'signal_2': 5, 'signal_6': 3, 'signal_4': 9, 'signal_3': 6, 'signal_9': 4, 'signal_7': 8},

{'signal_8': 1, 'signal_1': 7, 'signal_10': 5, 'signal_5': 2, 'signal_2': 5, 'signal_6': 3, 'signal_4': 9, 'signal_3': 6, 'signal_9': 4, 'signal_7': 8},
]
print({k:sum([x[k] for x in original_list if k in x]) for i in original_list for k,v in i.items()})

Output: 输出:

{'signal_8': 3, 'signal_1': 21, 'signal_10': 15, 'signal_5': 6, 'signal_2': 15, 'signal_6': 9, 'signal_4': 27, 'signal_3': 18, 'signal_9': 12, 'signal_7': 24}

Note that if there are missing signals, it will just consider it as zero 请注意,如果信号丢失,它只会将其视为零

Can you try below code 你能试试下面的代码吗?

basedict=siglist[0]
for k in basedict.keys():
    result=[currdict[k] for currdict in siglist]
    endval=sum(result)
    print("Key %s and sum of values %d"%(k,endval))

Output 产量

Key signal_9 and sum of values 12
Key signal_2 and sum of values 15
Key signal_8 and sum of values 3
Key signal_5 and sum of values 6
Key signal_7 and sum of values 24
Key signal_10 and sum of values 15
Key signal_1 and sum of values 21
Key signal_6 and sum of values 9
Key signal_4 and sum of values 27
Key signal_3 and sum of values 18

Note :- As we are sure that all keys in all dictionaries are same this solution works well. 注意: - 由于我们确信所有词典中的所有键都相同,因此该解决方案运行良好。 If you have a dictionary with non matching elements then it would result in KeyError . 如果你有一个非匹配元素的字典,那么它将导致KeyError So be aware of that limitation 所以要注意这个限制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM