DanielSon
DanielSon

Reputation: 1545

Summing the values of one element of a dictionary based upon the values of another element

Using Python, I have a list of two-element dictionaries which I would like to sum all the values of one element based upon the values of another element. ie.

[{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}]

This is the format (although there are much more entries than this), and for each different elev I would like to have the sum of all the area values that correspond to it. For the elev value of 0.0 I would like the sum of all values, same for elev of 0.1 etc

Upvotes: 0

Views: 69

Answers (4)

Blue Star
Blue Star

Reputation: 1952

Here's a short code sample that puts the relevant sums into a dictionary. It simply iterates over each dictionary in the input list, adding the area values to the appropriate elev key.

from collections import defaultdict

summed_dict = defaultdict(float)
for tup in input_list:
    summed_dict[tup['elev']] += tup['area']

Upvotes: 0

Frodon
Frodon

Reputation: 3775

Using a defaultdict, you don't need to the if/else statement:

from collections import defaultdict

mylist = [{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}]

sumdict = defaultdict(float)

for d in mylist:
    sumdict[d['elev']] += d.get('area', 0.0)

print dict(sumdict)

Upvotes: 1

PdevG
PdevG

Reputation: 3677

this is very easily achieved using pandas. Sample code:

import pandas as pd
df = pd.DataFrame([{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}])

which gives the following dataframe:

       area  elev
0  3.523558   0.0
1  3.523558   0.0

Then group by the elev columns and sum the area's:

desired_output = df.groupby('elev').sum()

which gives:

              area
elev          
0.0   7.047115

If you want you can then output this dataframe back to a dictionary in a useful format using:

desired_output.to_dict('index')

which returns

{0.0: {'area': 7.0471151003078063}}

Upvotes: 2

Harsha Biyani
Harsha Biyani

Reputation: 7268

You can try:

>>> l = [{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}]
>>> added_dict = {}
>>> for i in l:
      if i['elev'] in added_dict:
          added_dict[i['elev']] +=  i['area']
      else:
          added_dict[i['elev']] =  i['area']


>>> added_dict
{0.0: 7.0471151003078063}

Upvotes: 0

Related Questions