下面是试图生成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
当生成低于输出时
{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})
得到关键错误,任何帮助真的感谢
注意:这里有两种类型的dict,一种是{date':datetime.date日期(2011,8,14),'name':u'ab','total':8},另一个是{'name':u'ab','total':8,'type':u'UP'},。两者的区别在于关键。在第一个dict中找到日期键和另一个dict类型键
为什么你不应该得到一个键错误?您正在从
data
的第一行请求与type
关联的值,但是没有这样的键。你知道吗编辑:
@agf说这没什么用,让我再试一次。你知道吗
data
的第一行是在循环中
fetch
(顺便说一句,变量应该以名词命名,而不是动词;函数名是动词)被设置为第一行,并执行以下行:好吧,那条线不可能成功。在
fetch
中没有type
的条目,因此,如您所见,Python抛出了一个KeyError。更改数据以便有这样一个条目,或者更改代码以便不需要它。你知道吗尝试对“date”和“type”键执行边界检查:
更好的方法是检查dict中的每个元素是否都有您需要的所有键。你知道吗
相关问题 更多 >
编程相关推荐