Jesse Collier Jesse Collier - 6 months ago 29
Python Question

Dividing two numbers in a list, then storing that number as the value in a dictionary

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.


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.