Summing the values of one element of a dictionary based upon the values of another element
<p>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.</p>

<pre><code>[{'elev': 0.0, 'area': 3.52355755017894}, {'elev': 0.0, 'area': 3.5235575501288667}]
</code></pre>

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

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

<pre><code>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)
</code></pre>

python dictionary