[英]python: Dictionary Operation, KeyError: '0'
I want to extract information from a text file and store the data in a directionary. 我想从文本文件中提取信息并将数据存储在定向文件中。 The file records semicolon seperated values.
该文件记录以分号分隔的值。 That is, it records one property in one line, and the key and the value are seperated by a semicolon followed by a white space.
也就是说,它在一行中记录一个属性,并且键和值由分号和空格分隔。
def info_file_parser(info_file):
f=open(info_file,'rb')
info={}
for line in f:
line=line.rstrip()
mlist=line.split(": ")
if len(mlist)==2:
info[mlist[0]]=info[mlist[1]]
if __name__='__main__':
fname="/Users/me/info.txt"
info_file_parser(fname)
KeyError: '0'. KeyError:“ 0”。 What's wrong with that?
怎么了 Why can't I create keys by assignment?
为什么不能通过分配创建密钥?
You are trying to set a key in your dictionary with a key that doesn't exist. 您正在尝试使用不存在的键在字典中设置一个键。
In the if
statement of your function, shouldn't it be: 在函数的
if
语句中,它不应该是:
if len(mlist)==2:
info[mlist[0]]=mlist[1]
this line: 这行:
info[mlist[0]]=info[mlist[1]]
tries to store value from info dictonary with key mlist[1] and try this: 尝试使用关键字mlist [1]存储信息字典中的值,然后尝试以下操作:
info[mlist[0]]=mlist[1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.