[英]How do I sum a list of dictionaries by key?
I have a list of dictionaries.我有一个字典列表。 Each dictionary is a different size and can have different and similar key names.
每个字典都有不同的大小,并且可以有不同和相似的键名。
aList = [{
'Hits': 3,
'Blues': 4,
'Classical': 6,
'Metal': 8,
'Rock': 4,
'Funk': 5,
'Hip Hop': 5,
'Rap': 9,
'Easy Listening': 3
}, {
'Rap': 10,
'Jazz': 4,
'Hip Hop': 6,
'Dance': 3,
'Classical': 9,
'Blues': 3,
'Opera': 9,
'Easy Listening': 3,
'Country': 9,
'Pop': 2,
'Hits': 7
}, {
'Blues': 1,
'Metal': 9,
'Hits': 8,
'Dance': 2,
'Funk': 9,
'Jazz': 1,
'Classical': 2
}]
How do I store the sum of all the values corresponding to each key name?如何存储每个键名对应的所有值的总和?
You definitely need to use built-in Counter
class from collections
module.您肯定需要使用
collections
模块中的内置Counter
class。 Here is working code example:这是工作代码示例:
from collections import Counter
aList = [{
'Hits': 3,
'Blues': 4,
'Classical': 6,
'Metal': 8,
'Rock': 4,
'Funk': 5,
'Hip Hop': 5,
'Rap': 9,
'Easy Listening': 3
}, {
'Rap': 10,
'Jazz': 4,
'Hip Hop': 6,
'Dance': 3,
'Classical': 9,
'Blues': 3,
'Opera': 9,
'Easy Listening': 3,
'Country': 9,
'Pop': 2,
'Hits': 7
}, {
'Blues': 1,
'Metal': 9,
'Hits': 8,
'Dance': 2,
'Funk': 9,
'Jazz': 1,
'Classical': 2
}]
counter = Counter()
for d in aList:
counter.update(d)
print(dict(counter))
# Outputs:
# {'Hits': 18, 'Blues': 8, 'Classical': 17, 'Metal': 17, 'Rock': 4, 'Funk': 14, 'Hip Hop': 11, 'Rap': 19, 'Easy Listening': 6, 'Jazz': 5, 'Dance': 5, 'Opera': 9, 'Country': 9, 'Pop': 2}
You can use collections. Counter
您可以使用
collections. Counter
collections. Counter
from collections import Counter
totals = Counter()
for elem in aList:
totals.update(elem)
print(totals)
Counter({'Rap': 19, 'Hits': 18, 'Classical': 17, 'Metal': 17, 'Funk': 14, 'Hip Hop': 11, 'Opera': 9, 'Country': 9, 'Blues': 8, 'Easy Listening': 6, 'Jazz': 5, 'Dance': 5, 'Rock': 4, 'Pop': 2})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.