Sum of values in a dict
I want to have sum of values in a dict.
Below is the code which I have written.results = collections.defaultdict(dict)
for main, month, tot in list_data:
d = results[main]
d[month] = tot
d.setdefault('total', 0)
d['total'] += tot
result_output = dict(results)
Above code gives below ouput:
{u'Apple': {'January': 17, 'February': 1, 'total': 19, 'March': 1},
u'Oranges': {'total': 1, 'March': 1},
u'Graphes': {'January': 24, 'February': 1, 'total': 66, 'March': 41}}
But I want output like this:
{u'Apple': {'January': 17, 'February': 1, 'total': 19, 'March': 1},
u'Oranges': {'total': 1, 'March': 1},
u'Graphes': {'January': 24, 'February': 1, 'total': 66, 'March': 41, 'April': 1},
u'grandtota开发者_JAVA百科l': {'January': 41 , 'February': 3, 'March': 43, 'April':1 }}
I was just wondering if anyone could help me with this problem I'm having. I would really appreciate it.
How about this? (Untested)
from collections import defaultdict
from functools import partial
results = defaultdict(partial(defaultdict, int))
for main, month, tot in list_data:
results[main][month] += tot
results[main]["total"] += tot
results[u"grandtotal"][month] += tot
result_output = dict((k, dict(v)) for k, v in results.items())
EDIT: result_output now has dict values instead of defaultdict values.
You can try that, not tested...
gt = collections.defaultdict(int) # get a new dict
results = collections.defaultdict(dict)
for main, month, tot in list_data:
d = results[main]
d[month] = tot
gt[month]+=tot # populate it
d.setdefault('total', 0)
d['total'] += tot
result_output = dict(results)
results_output['grand_total'] = gt # save it
So you want to add a grandtotal.
If you start with a structure like:
starting_data = {u'Apple': {'January': 17, 'February': 1, 'total': 19, 'March': 1},
u'Oranges': {'total': 1, 'March': 1},
u'Graphes': {'January': 24, 'February': 1, 'total': 66, 'March': 41}}
You can do something like
grand_total = defaultdict(int) # makes it default to 0
for fruit, fruitdict in starting_data.items():
for month, total in fruitdict.items():
grand_total[month] += total
starting_data[u'grand_total'] = dict(grand_total)
This has been tested and gives
{u'Apple': {'February': 1, 'January': 17, 'March': 1, 'total': 19},
u'Graphes': {'February': 1, 'January': 24, 'March': 41, 'total': 66},
u'Oranges': {'March': 1, 'total': 1},
u'grand_total': {'February': 2, 'January': 41, 'March': 43, 'total': 86}}
Obviously you don't need to go through the list again and could aggregate earlier; but I like to test and don't know the format of the input data.
Using collections.Counter:
import collections
results = collections.Counter()
a = {u'Apple': {'January': 17, 'February': 1, 'total': 19, 'March': 1},
u'Oranges': {'total': 1, 'March': 1},
u'Graphes': {'January': 24, 'February': 1, 'total': 66, 'March': 41}}
for counts in a.values():
results.update(counts)
print results # Counter({'total': 86, 'March': 43, 'January': 41, 'February': 2})
精彩评论