我想根据另一个键值等于字典列表中的一个值。
stackOverflow更简单的问题答案只是总和总和: I have a very big list of dictionaries and I want to sum the insides
例如:如果我们有
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 = [{'year': 2013, 'totalsnow': 339.3},
{'year': 2012, 'totalsnow': 156.4},
{'year': 1951, 'totalsnow': 86.6}]
这是我的代码:
for i in range(len(lst)):
while lst[i]['year']:
sum(value['snow'] for value in lst)
那么它会出错,输出
582.3000000000001
如何做到对了?请样品并解释。我是python的新手。
答案 0 :(得分:4)
使用字典跟踪每年的雪; collections.defaultdict()
object是理想的选择:
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)]
这首先创建一个defaultdict()
对象,它将为尚不存在的键创建新的float()
个对象(值0.0)。它总结了你每年的价值。
最后一行创建所需的结构,按年份降序排列。
演示:
>>> 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}]