我希望在词典中加上值的总和 下面是我写的代码。
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 }}
我只是想知道是否有人可以帮我解决这个问题。我真的很感激。
答案 0 :(得分:1)
这个怎么样? (未测试)
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())
编辑:result_output现在有dict值而不是defaultdict值。
答案 1 :(得分:1)
你可以尝试,而不是测试...
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
答案 2 :(得分:0)
所以你想要添加一个Grandtotal。
如果您从以下结构开始:
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}}
您可以执行类似
的操作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)
已经过测试并给出了
{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}}
显然你不需要再次浏览列表并且可以更早地聚合;但我喜欢测试并且不知道输入数据的格式。
答案 3 :(得分:0)
使用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})