[英]sum of one value in the list of dictionary based on one key in dict
I want to sum one value in the list of dictionary based on another key value is equal. 我想根据另一个键值等于等于字典列表中的一个值。
stackOverflow much easier question answer for just sum the total value: I have a very big list of dictionaries and I want to sum the insides 只求总值的总和就容易了stackOverflow问题答案: 我有一个很大的词典列表,我想对内部求和
For example: if we have 例如:如果我们有
lst = [{'year': 2013, 'snow': 64.8, 'month': 1},
{'year': 2013, 'snow': 66.5, 'month': 2},
{'year': 2013, 'snow': 68.3, 'month': 12},
{'year': 2013, 'snow': 68.8, 'month': 3},
{'year': 2013, 'snow': 70.9, 'month': 11},
{'year': 2012, 'snow': 76.8, 'month': 7},
{'year': 2012, 'snow': 79.6, 'month': 5},
{'year': 1951, 'snow': 86.6, 'month': 12}]
to get the sum of snow fall in that year: 得到当年降雪的总和:
the output should: 输出应为:
snowfall = [{'year': 2013, 'totalsnow': 339.3},
{'year': 2012, 'totalsnow': 156.4},
{'year': 1951, 'totalsnow': 86.6}]
Here is my code: 这是我的代码:
for i in range(len(lst)):
while lst[i]['year']:
sum(value['snow'] for value in lst)
then it will goes wrong, output 然后会出错,输出
582.3000000000001
How to get it right? 如何正确处理? Please be sample and explain as well.
请样本并解释。 I am new to python.
我是python的新手。
Use a dictionary to track snow-per-year; 使用字典来追踪每年的降雪量; a
collections.defaultdict()
object is ideal here: 一个
collections.defaultdict()
对象在这里很理想:
from collections import defaultdict
snowfall = defaultdict(float)
for info in lst:
snowfall[info['year']] += info['snow']
snowfall = [{'year': year, 'totalsnow': snowfall[year]}
for year in sorted(snowfall, reverse=True)]
This first creates a defaultdict()
object that'll create new float()
objects (value 0.0) for keys that don't exist yet. 这首先创建一个
defaultdict()
对象,该对象将为尚不存在的键创建新的float()
对象(值0.0)。 It sums the values per year for you. 它汇总了您每年的价值。
The last lines create your desired structure, sorted by year in descending order. 最后几行创建所需的结构,并按年份降序排列。
Demo: 演示:
>>> from collections import defaultdict
>>> lst = [{'year': 2013, 'snow': 64.8, 'month': 1},
... {'year': 2013, 'snow': 66.5, 'month': 2},
... {'year': 2013, 'snow': 68.3, 'month': 12},
... {'year': 2013, 'snow': 68.8, 'month': 3},
... {'year': 2013, 'snow': 70.9, 'month': 11},
... {'year': 2012, 'snow': 76.8, 'month': 7},
... {'year': 2012, 'snow': 79.6, 'month': 5},
... {'year': 1951, 'snow': 86.6, 'month': 12}]
>>> snowfall = defaultdict(float)
>>> for info in lst:
... snowfall[info['year']] += info['snow']
...
>>> snowfall = [{'year': year, 'totalsnow': snowfall[year]}
... for year in sorted(snowfall, reverse=True)]
>>> from pprint import pprint
>>> pprint(snowfall)
[{'totalsnow': 339.30000000000007, 'year': 2013},
{'totalsnow': 156.39999999999998, 'year': 2012},
{'totalsnow': 86.6, 'year': 1951}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.