简体   繁体   中英

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

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.

Use a dictionary to track snow-per-year; a collections.defaultdict() object is ideal here:

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. 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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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