从未预料到的KeyError收到

时间:2014-04-08 14:56:52

标签: python dictionary hashmap

我在分配KeyError变量时收到line_to_be_added。可能是什么原因?

for key in PL_HASH_ON_FIRST_TWO_PARTS.keys():
    total_count=0
    print key, '\n'
    for pl_name in sorted(PL_HASH_ON_FIRST_TWO_PARTS[key]):
        print pl_name,'\n'
        count = PL_DICT_COUNT[pl_name]
        plTable = plTable + "<tr><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td></tr>"%(pl_name, PL_NAME_DICT[pl_name][last_six_months[7]], PL_NAME_DICT[pl_name][last_six_months[6]], PL_NAME_DICT[pl_name][last_six_months[5]], PL_NAME_DICT[pl_name][last_six_months[4]], PL_NAME_DICT[pl_name][last_six_months[3]], PL_NAME_DICT[pl_name][last_six_months[2]], PL_NAME_DICT[pl_name][last_six_months[1]], PL_NAME_DICT[pl_name][last_six_months[0]], count)
        if key in count_bag_wise:
            for i in range(0,7):
                print last_six_months[i],'\n'
                count_bag_wise[key][last_six_months[i]]+=PL_NAME_DICT[pl_name][last_six_months[i]]
        else:
            count_bag_wise[key]=dict()
            for i in range(0,7):
                count_bag_wise[key][last_six_months[i]]=0
                count_bag_wise[key][last_six_months[i]]+=PL_NAME_DICT[pl_name][last_six_months[i]]
        TOTAL_COUNT += count
        total_count += count
    line_to_be_added="<tr><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td></tr>"%(pl_name.split('.')[0]+'.'+pl_name.split('.')[1]+'.*', count_bag_wise[key][last_six_months[7]],count_bag_wise[key][last_six_months[6]], count_bag_wise[key][last_six_months[5]],count_bag_wise[key][last_six_months[4]],count_bag_wise[key][last_six_months[3]], count_bag_wise[key][last_six_months[2]],count_bag_wise[key][last_six_months[1]],count_bag_wise[key][last_six_months[0]], total_count)
    print line_to_be_added
    plTable = plTable +line_to_be_added

1 个答案:

答案 0 :(得分:0)

您从未设置last_six_months[7]密钥:

for i in range(0,7):
    count_bag_wise[key][last_six_months[i]]=0
    count_bag_wise[key][last_six_months[i]]+=PL_NAME_DICT[pl_name][last_six_months[i]]

范围包括7(结束值是独占的)。

但您的line_to_be_added代码使用:

count_bag_wise[key][last_six_months[7]]