input_file = open('dictionaryHmong.txt')
dictionary = {}
for lines in input_file:
information = lines.split(',')
dictionary[lines[0]] = {'Hmong': lines[1], 'English': lines[2]}
Error:
<module>
dictionary[lines[0]] = {'Hmong': lines[1], 'English': lines[2]}
builtins.IndexError: string index out of range
So I am trying to set up a dictionary from a text file but I have tried multiple ways of doing it and this was my last try with no luck.
The file looks like this:
1,raws li,as
2,kuv,I
3,nws,his
and so on
I need to get this to work before i start the rest of the program.
Thanks in advance!
dictionary[lines[0]] = {'Hmong': lines[1], 'English': lines[2]}
I believe you want
information here instead of
lines.
When faced with such issues you can simply use
print to see what kind of data you are dealing with and thus find mistakes immediately.
As for working with files, it is recommended to use context manager (
with keyword). See an example in
the docs.
so something like this but I am still getting a error.
dictionary = {}
with open('dictionaryHmong.txt', 'r') as input_file:
for lines in input_file:
info = lines.split(',')
dictionary[info[0]] = {'Hmong': info[1], 'English': info[2]}
print (dictionary)
Error:
dictionary[info[0]] = {'Hmong': info[1], 'English': info[2]}
builtins.IndexError: list index out of range
I don't understand why it is saying it is out of range. there should be 3 values it is splitting up on each line.
Why not insert a print after assigning info, to see what value it holds.
I did and it does not make any sense. So back to the drawing board.
['ÿþ1\x00', '\x00r\x00a\x00w\x00s\x00 \x00l\x00i\x00', '\x00a\x00s\x00']
['\x00']
I figured it out my text file was saved as a unicode file instead of ANSI. At least when I switched it that fixed the problem with what was printing. Thanks.
Well done solving the issue, thanks for reporting the solution.