python中的KeyError 43L

时间:2015-11-21 10:25:50

标签: python dictionary keyerror

我想在另一个字典中为字典分配一个列表,但是我得到一个键错误 你可以在这里找到这个文件 https://www.dropbox.com/s/9n35b41rzuxjkk8/plan1.txt?dl=0

Code, Title, Lec, Lab, Cr, Prereq, Year, Semester

ARAB110 ,  Arabic Language Skills I ,  3 ,  0 , 3,  - ,  1 ,  1 
CHEMY101 ,  General Chemistry I ,  3 ,  3 , 4,  - ,  2 ,  2 
ENGL154 ,  Language Development I ,  3 ,  0 , 3,  - ,  1 ,  1 
ENGL155 ,  Language Development II ,  3 ,  0 , 3,  ENGL154 ,  1 ,  2 
ENGL219 ,  Technical Report Writing ,  3 ,  0 , 3,  ENGL155 ,  2 ,  1 

我想为每年创建一个词典,每年内部每个学期的词典都包含本学期所有代码的列表

curri = read_csv('senior_data/plan1.txt')
curri = curri.sort([' Year',' Semester '],ascending=[1,1]) 

cur = {}
cur['1']={}
cur['2']={}
cur['3']={}
cur['4']={}

cur['1']['1'] = {}
cur['1']['2'] = {}
cur['2']['1'] = {}
cur['2']['2'] = {}
cur['3']['1'] = {}
cur['3']['2'] = {}
cur['3']['3'] = {}
cur['4']['1'] = {}
cur['4']['2'] = {}


i=0
c_list = []
for xxx in cur:
    for y in cur[xxx]:
        print (xxx+" "+y)
        for row in curri.iterrows():
            if(str(curri[' Year'][i]) == xxx and str(curri[' Semester '][i] == y)):   
                print (xxx+":"+y+ curri['Code'][i])
                c_list.append(curri['Code'][i])
            i=i+1
            cur[xxx][y] = c_list
            c_list = []

当我删除第三个循环时,它工作正常!

这是输出:

1 1
1:1 ARAB110 
1:1 ENGL154 
1:1 ENGL155 
1:1 ISLM101 
1:1 ITCS101 
1:1 ITCS102 
1:1 MATHS101 
1:1 MATHS102 
1:1 PHYCS101 
1:1 PHYCS102 
1 2

错误是

KeyError: 42L

---> 24             if(str(curri[' Year'][i]) == xxx and str(curri[' Semester ']

1 个答案:

答案 0 :(得分:0)

i的增量应该在最内循环中发生。

假设行是字典,这可能有效:

c_list = []
for xxx in cur:
    for y in cur[xxx]:
        print (xxx+" "+y)
        for row in curri.iterrows():
            if(str(row[' Year']) == xxx and str(row[' Semester '] == y)):   
                print (xxx+":"+y+ row['Code'])
                c_list.append(row['Code'])
            cur[xxx][y] = c_list
            c_list = []

如果没有试试这个:

c_list = []
for xxx in cur:
    for y in cur[xxx]:
        print (xxx+" "+y)
        i = 0
        for row in curri.iterrows():
            if(str(curri[' Year'][i]) == xxx and str(curri[' Semester '][i] == y)):   
                print (xxx+":"+y+ curri['Code'][i])
                c_list.append(curri['Code'][i])
            i=i+1
            cur[xxx][y] = c_list
            c_list = []

在Python中,通常不需要手动递增索引:

c_list = []
for xxx in cur:
    for y in cur[xxx]:
        print (xxx+" "+y)
        for i, row in enumerate(curri):
            if(str(curri[' Year'][i]) == xxx and str(curri[' Semester '][i] == y)):   
                print (xxx+":"+y+ curri['Code'][i])
                c_list.append(curri['Code'][i])
            cur[xxx][y] = c_list
            c_list = []