下面是使用尝试生成dict的dict列表
data = [
{'date': datetime.date(2011, 8, 14), 'name': u'ab', 'total': 8},
{'date': datetime.date(2011, 8, 15), 'name': u'ab', 'total': 8},
{'date': datetime.date(2011, 8, 16), 'name': u'ab', 'total': 8},
{'date': datetime.date(2011, 8, 17), 'name': u'ab', 'total': 8},
{'date': datetime.date(2011, 8, 18), 'name': u'ab', 'total': 8},
{'date': datetime.date(2011, 8, 19), 'name': u'ab', 'total': 8},
{'date': datetime.date(2011, 8, 20), 'name': u'ab', 'total': 8},
{'date': datetime.date(2011, 8, 21), 'name': u'ab', 'total': 8},
{'date': datetime.date(2011, 8, 18), 'name': u'aj', 'total': 0},
{'date': datetime.date(2011, 8, 14), 'name': u'ap', 'total': 8},
{'date': datetime.date(2011, 8, 15), 'name': u'ap', 'total': 8},
{'date': datetime.date(2011, 8, 16), 'name': u'ap', 'total': 8},
{'date': datetime.date(2011, 8, 17), 'name': u'ap', 'total': 8},
{'name': u'ab', 'l_total': 8, 'type': u'UP'},
{'name': u'ab', 'l_total': 8, 'type': u'PL'},
{'name': u'fk', 'l_total': 29, 'type': u''},
{'name': u'jw', 'l_total': 1, 'type': u'PD'},
{'name': u'uk', 'l_total': 16, 'type': u'UP'},
{'name': u'sk', 'l_total': 24, 'type': u'PL'},
{'name': u'ss', 'l_total': 8, 'type': u'PL'},
{'name': u'sst', 'l_total': 8, 'type': u'PL'}]
results = collections.defaultdict(dict)
for fetch in data:
user = fetch['name']
hrs = fetch['total']
row = results[user]
new_y = fetch['type']
row['new_y'] = fetch['l_total']
row['user'] = user
dt_string = str(fetch['date'])
if dt_string in fetch and row[dt_string] != hr:
raise Exception, "Contradiction: '%s' on '%s'" % (user, dt_string)
row[dt_string] = hrs
row.setdefault('Total', 0)
row['Total'] += hrs
Run Code Online (Sandbox Code Playgroud)
同时产生低于输出
{u'ap': {'Total': 32, 'user': u'ap', '2011-08-17': 8,
'2011-08-16': 8, '2011-08-15': 8, '2011-08-14': 8,
'up': 8, 'PL':8})
Run Code Online (Sandbox Code Playgroud)
得到关键错误,任何帮助真的很感激
注意:在这里你可以找到两种类型的词组:{'date':datetime.date(2011,8,14),'name':u'ab','total':8},另一种是{'name': u'ab','total':8,'type':u'UP'} ,. 两者之间的区别是关键.在第一个词典中,您可以找到日期键和另一个词典类型键
为什么不能得到KeyError?你要求type第一行的相关值,data并且没有这样的键.
编辑:
@agf说这没什么用,所以让我再试一次.
第一行data是
{'date': datetime.date(2011, 8, 14), 'name': u'ab', 'total': 8}
Run Code Online (Sandbox Code Playgroud)
在循环中fetch(顺便说一句,变量应该以名词命名,而不是动词;函数名称是动词)设置为第一行,并执行以下行:
new_y = fetch['type']
Run Code Online (Sandbox Code Playgroud)
好吧,那条线不能成功.不存在用于入门type的fetch话,你已经看到,Python中抛出一个KeyError异常.更改数据,以便有这样的条目或更改代码,因此它不需要它.