[英]KeyError Why is dictionary empty?
I wanna make a dictionary that has name
's key & data. 我想制作一个包含
name
的键和数据的字典。 In views.py I wrote 我在views.py中写道
data_dict ={}
def try_to_int(arg):
try:
return int(arg)
except:
return arg
def main():
book4 = xlrd.open_workbook('./data/excel1.xlsx')
sheet4 = book4.sheet_by_index(0)
data_dict_origin = OrderedDict()
tag_list = sheet4.row_values(0)[1:]
for row_index in range(1, sheet4.nrows):
row = sheet4.row_values(row_index)[1:]
row = list(map(try_to_int, row))
data_dict_origin[row_index] = dict(zip(tag_list, row))
print(data_dict_origin)
for value in data_dict_origin.values():
if value['name'] in data_dict_origin:
data_dict[value['name']].update(value)
else:
data_dict[value['name']] = value
print(data_dict)
main()
print(data_dict_origin)
gives: print(data_dict_origin)
给出:
OrderedDict([(1, {'user_id': '100', 'group': 'A', 'name': 'Tom', 'dormitory': 'C'})])
So, I really cannot understand why this error happens. 因此,我真的不明白为什么会发生此错误。 I tried other things like:
我尝试了其他事情,例如:
for value in data_dict.values():
if value['name'] in data_dict:
data_dict[value['name']].update(value)
else:
data_dict[value['name']] = value
{}
was shown. {}
。 How should I fix this? 我该如何解决?
Simple is better than complex.
简单胜于复杂。
from collections import defaultdict
data_dict = defaultdict(dict)
def try_to_int(arg):
try:
return int(arg)
except:
return arg
def main():
book4 = xlrd.open_workbook('./data/excel1.xlsx')
sheet4 = book4.sheet_by_index(0)
tag_list = sheet4.row_values(0)[1:]
for row_index in range(1, sheet4.nrows):
row = sheet4.row_values(row_index)[1:]
row = list(map(try_to_int, row))
value = dict(zip(tag_list, row))
print(value)
if value.get('name', ''):
data_dict[value['name']].update(value)
print(data_dict)
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.