Reputation: 59
I need to read in lines from a text file (I already have done this). The lines are in the same format: "Name", "number", "number". I read in the lines and put each line in a separate lists, to make a lists of lists. I need to divide the third number by the second number from each line, then store the resulting number as a value in a dictionary, with the "Name" as the key.
for line in f:
list_words = [line.strip().split(',') for line in f]
That is what I have so far, assuming f is a textfile that is already read in. I'm using Python 3.
Upvotes: 0
Views: 66
Reputation: 78554
You can use a dictionary comprehension:
list_words = [line.strip().split(',') for line in f]
d = {lst[0]: float(lst[2])/float(lst[1]) for lst in list_words}
Note that the list comprehension that creates list_words
eliminates the need for the enclosing for
loop.
Caveat: A ZeroDivisionError
will be raised if one of your divisors has value zero.
An alternative approach is to add new key-value pairs at each iteration of a for
loop on list_words
:
d = {}
for lst in list_words:
try:
d[lst[0]] = float(lst[2])/float(lst[1])
except ZeroDivisionError:
pass
Upvotes: 3
Reputation: 1654
Something like
d = {l[0]:float(l[1])/float(l[2]) for l in list_words}
will create a dictionary keyed on the first (i.e. position 0) item.
Notes:
Upvotes: 0