2017-07-06 42 views
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} 

现在,我想总结一下,让我得到的,在不同的位置计数的分裂每个日期,我困在这里。

回答

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()} 
+0

这返回** 'INT' 对象不是可迭代**在第2行错误(对于k,(W,T,L)详细:) – Newbie

+0

@Newbie在违规循环之前放置一个'print(detail)'来检查'detail'变量的值。也许你用一个'int'意外覆盖了它? –

+0

好吧..但我想波士顿,纽约等的数量(发生次数),而不是他们的关键。 – 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)]} 
+0

这工作。谢谢。 – Newbie

相关问题