尝试从字典中获取值时的keyError,Python

时间:2017-05-14 01:29:05

标签: python python-2.7 dictionary

我可以在第二个循环中迭代并写入文件而没有任何问题。但是在第三个循环中,当我尝试调用一个值时,我得到了

R.write(str(dictList[s])+'\n')
KeyError: '<http://www.Department17.University9.edu/GraduateStudent72>'

以下是代码:

f = open('advisor', 'rw')
e = open('dictionary.txt', 'rw')
R = open ('encodedAdvisor.txt', 'w')

import re

dictList={'key':'val'}
for line1 in e:
    kv=line1.split(',')
    key=str(kv[1])  
    val=str(kv[0])
    dictList.update({key:val})
for k, v in dictList.iteritems():
    R.write(str(k)+':'+v+':'+'\n') 
for line2 in f:
    spo = re.findall(r'(<.*?>)', line2)
    s = str(spo[0].strip())
    o = str(spo[1].strip())
    R.write(str(dictList[s])+'\n')

顾问档案:

advisor(<http://www.Department17.University9.edu/GraduateStudent71>,<http://www.Department17.University9.edu/AssociateProfessor7>)
advisor(<http://www.Department5.University9.edu/GraduateStudent97>,<http://www.Department5.University9.edu/AssociateProfessor0>)
advisor(<http://www.Department3.University9.edu/GraduateStudent60>,<http://www.Department3.University9.edu/FullProfessor6>)
advisor(<http://www.Department17.University9.edu/GraduateStudent70>,<http://www.Department17.University9.edu/AssistantProfessor2>)
advisor(<http://www.Department9.University9.edu/UndergraduateStudent260>,<http://www.Department9.University9.edu/FullProfessor9>)
advisor(<http://www.Department3.University9.edu/GraduateStudent59>,<http://www.Department3.University9.edu/AssociateProfessor5>)

字典文件:

GraduateStudent21158,<http://www.Department17.University9.edu/GraduateStudent66>
GraduateStudent21159,<http://www.Department17.University9.edu/GraduateStudent67>
GraduateStudent21160,<http://www.Department17.University9.edu/GraduateStudent68>
GraduateStudent21161,<http://www.Department17.University9.edu/GraduateStudent69>
GraduateStudent21162,<http://www.Department17.University9.edu/GraduateStudent7>
GraduateStudent21163,<http://www.Department17.University9.edu/GraduateStudent70>
GraduateStudent21164,<http://www.Department17.University9.edu/GraduateStudent71>
GraduateStudent21165,<http://www.Department17.University9.edu/GraduateStudent72>
GraduateStudent21166,<http://www.Department17.University9.edu/GraduateStudent73>
GraduateStudent21167,<http://www.Department17.University9.edu/GraduateStudent74>    

1 个答案:

答案 0 :(得分:1)

我认为你的字典文件中的每一行都有尾随空格。我选择文本时会注意到它们。如果这是在您的实际文件中,这将引发错误,因为在键查找期间字符串将不匹配。试试这个:

for line1 in e:
    line1 = line1.strip()
    ...

否则,请测试您的预期密钥实际上位于dictList密钥中:

expected = "<http://www.Department17.University9.edu/GraduateStudent72>"
assert expected in dictList

如果引发异常,您可以使用difflib跟踪差异。任何打印的+-都会显示差异。这可以帮助您解决正在发生的事情。

import difflib

actual = [k for k in dictList if "72" in k][0]
for i in difflib.ndiff(expected, actual):
    print(i, end="")