创建一个字典,从列表中获取摘要值 / 合并两个不同的字典以总结价值

3

我是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)]}

我希望以这种格式,因为我想为每个日期(键)和位置点(值)生成地图(可视化效果)。
我最终创建了两个不同的字典,看起来像这样 -
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}

现在,我想总结一下,为了得到每个日期的不同位置的拆分计数,并且我现在被卡住了。

2个回答

3
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()}

在第2行出现了“'int' object is not iterable”错误。(for k, (w, t, l) in detail:) - Newbie
@新手 在有问题的循环前加上print(detail),检查detail变量的值。也许你不小心用int覆盖了它? - AGN Gazer
好的,但我想要波士顿、纽约等地的计数(出现次数),而不是它们的键。 - Newbie

1

利用Python集合 defaultdictCounter

from collections import defaultdict, Counter
summary = defaultdict(list)
for item in detail:
  summary[item[1][1].split('T')[0]].append(item[1][2])

details_summary = {str(k):[(x,y) for x,y in Counter(v).iteritems()] for k,v in summary.iteritems()}
print details_summary
{'2017-07-06': [('san francisco', 1), ('seattle', 1)], '2017-07-04': [('new york', 1)], '2017-07-03': [('boston', 2), ('NOLOCATION', 1)]}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接