Compsciguy
Compsciguy

Reputation: 59

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.

Upvotes: 0

Views: 66

Answers (2)

Moses Koledoye
Moses Koledoye

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

TimGJ
TimGJ

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:

  1. If you've just read the file in, Python will regard the two number as strings, hence the need to convert them to floats.
  2. You really should also consider some sort of error checking - e.g. what if there aren't exactly three items on the line? What if the numbers can't be parsed (e.g. what would happen if something in the name field contained a comma?)

Upvotes: 0

Related Questions