KeyError为什么字典为空?

时间:2017-09-11 12:35:45

标签: python dictionary

我想制作一本有name键和字母的词典。数据。在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)给出:

OrderedDict([(1, {'user_id': '100', 'group': 'A', 'name': 'Tom', 'dormitory': 'C'})])

所以,我真的不明白为什么会发生这种错误。 我尝试过其他的事情:

for value in data_dict.values():
            if value['name'] in data_dict:
                data_dict[value['name']].update(value)
            else:
                data_dict[value['name']] = value
显示了{p> {}。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

  

简单比复杂更好。

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