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'grandtotal': {'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)
EDIT: result_output now has dict values instead of defaultdict values.