我想要在字典中有值的总和。
以下是我写的代码。字典中的值的总和
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)
上面的代码,给出以下输出继电器:
{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}}
但我想这样的输出:
{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 }}
我只是想知道,如果有人可以帮助我解决这个问题我有。我真的很感激。
一般情况下,如果你能给样本数据会有所帮助;即使它只说三项。 – 2011-05-21 21:39:03