Reputation: 127
I am trying to create a function that opens a file for reading, skips the first line because it is the header, gets every line and splits at ':' to get keys and values to put into a dictionary and then return that dictionary. My problem is that my function is just giving me an empty dictionary. How do I fix this?
ex from line 2: 'Bulbasaur': (1, 'Grass', 'Poison', 1, False)
'Bulbasaur' is the key and everything after colon is the value for that key.
So I need to return: my_dict={'bulbasaur':(1, 'Grass', 'Poison', 1, False)}
Here is my function:
def read_info_file(filename):
f=open(filename, 'r') #open file for reading
lines=f.readlines()[1:] #skip first line
d={} #create dictionary
for lines in f: #iterate for all lines
x=lines.split(':') #split at colon
a=x[0] #map keys to values
b=x[1]
d[a]=b #add to dictionary
return d #return dictionary
Upvotes: 1
Views: 128
Reputation: 1477
Change it to:
lines=f.readlines()[1:] #skip first line
d={} #create dictionary
for line in lines: #iterate for all lines
if ':' in line:
x=line.strip().split(':') #split at colon
a=x[0] #map keys to values
b=x[1]
d[a]=b #add to dictionary
return d #return dictionary
...
Otherwise if no colon in the line, you will get IndexError
.
Upvotes: 0
Reputation: 78700
f = open(filename, 'r')
gives your an iterator over the lines of the file.
After you do lines = f.readlines()[1:]
the iterator has yielded all its values because the invocation of readlines
calls __next__
on f
until there are no lines left.
Now here's the problem: After you have done all that, you issue for lines in f
i.e. you try to loop over the iterator again. But since it is empty, the body of your for
loop will never be executed.
There are several ways to fix your code. The most straight forward is to loop over your list lines
, not f
, i.e. something like for line in lines
.
On the other hand, it does not seem like you need a full fledged list of all the lines prior to iteration, so consider just looping over f
directly without calling readlines
beforehand.
Upvotes: 2