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'. 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 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:
info[mlist[0]]=mlist[1]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.