3 回答
TA贡献1836条经验 获得超3个赞
from collections import defaultdict, Counter, OrderedDict
ld = [{'key': '2018-05-10', 'vals': {'Clicks': 229, 'Link Clicks': 210}}, {'key': '2018-05-11', 'vals': {'Clicks': 365, 'Link Clicks': 379}}, {'key': '2018-05-10', 'vals': {'Clicks': 139, 'Link Clicks': 11}}, {'key': '2018-05-11', 'vals': {'Clicks': 1348, 'Link Clicks': 73}}]
out=defaultdict(Counter())
for d in ld:
out[d['key']].update(d['vals'])
new = OrderedDict(sorted(out.items()))
print(new)
# OrderedDict([('2018-05-10', Counter({'Clicks': 368, 'Link Clicks': 221})), ('2018-05-11', Counter({'Clicks': 1713, 'Link Clicks': 452}))])
TA贡献1801条经验 获得超8个赞
from pprint import pprint
from collections import Counter, OrderedDict
d = {
'2018-05-10': [
{'Clicks': 229, 'Link Clicks': 210},
{'Clicks': 139, 'Link Clicks': 11}
],
'2018-05-11': [
{'Clicks': 365, 'Link Clicks': 379},
{'Clicks': 1348, 'Link Clicks': 73}
],
}
m = OrderedDict()
for k, v in d.items():
m[k] = Counter()
for i in v:
m[k].update(i)
m[k] = dict(m[k])
# or if you want to keep the 'vals' key and list:
# m[k] = [{"vals": dict(m[k])}]
pprint(m)
输出:
OrderedDict([('2018-05-11', {'Clicks': 1713, 'Link Clicks': 452}),
('2018-05-10', {'Clicks': 368, 'Link Clicks': 221})])
TA贡献1851条经验 获得超3个赞
您可以使用嵌套字典理解。相关c_type键(即Clicks&Link Clicks)是从每个日期的第一个列表中派生的。否则,该方法自然会接受任意数量的类别。
res = {k: {'vals': {c_type: sum(item[c_type] for item in v) for c_type in v[0]}}
for k, v in dd.items()}
{'2018-05-10': {'vals': {'Clicks': 368, 'Link Clicks': 221}},
'2018-05-11': {'vals': {'Clicks': 1713, 'Link Clicks': 452}}}
添加回答
举报