我是 python 新手,使用字典和列表。 这是列表
detail = [(1, [u'apple', u'2017-07-03T08:03:32Z', 'boston']),
(2, [u'orange', u'2017-07-03T08:58:35Z', 'NOLOCATION']),
(3, [u'grape', u'2017-07-03T12:14:12Z', 'boston']),
(4, [u'cherry', u'2017-07-04T13:16:44Z', 'new york']),
(5, [u'strawberry', u'2017-07-06T10:56:22Z', 'san francisco']),
(6, [u'plum', u'2017-07-06T10:56:22Z', 'seattle'])]
我想对此进行总结,以便 - 对于每个日期,我都会得到每个位置的计数拆分。像这样的 -
details_summary = {'2017-07-03':[(boston,2), (NOLOCATION,1)], '2017-07-04':
[new york,1], '2017-07-06':[(san francisco,1),(seattle,1)]}
我想要这种格式,因为我想为每个日期(键)和位置点(值)生成 map (可视化)。
我最终创建了两个看起来像这样的不同词典 -
location = {u'boston': 2, 'NOLOCATION': 1, u'new york': 1, u'san francisco':
1, u'seattle': 1}
date = {'2017-07-03':3, '2017-07-04':1, '2017-07-06':2}
现在,我想总结一下,以便我得到每个日期在不同位置的计数拆分,我被困在这里。
最佳答案
from collections import Counter
d = {}
for k, (w, t, l) in detail:
date = t.split('T')[0] # you can choose to enhance date "isolation"
if date in d:
d[date].append(l)
else:
d[date] = [l]
details_summary = {k: Counter(d[k]).items() for k in d.keys()}
关于python - 创建一个具有列表汇总值的字典/合并两个不同的字典以汇总值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44939710/