Creating a dictionary from a .txt file

Chris Angelico rosuav at gmail.com
Sun Mar 31 18:06:18 CEST 2013


On Mon, Apr 1, 2013 at 2:52 AM, C.T. <swilks06 at gmail.com> wrote:
> After playing around with the code, I came up with the following code to get everything into a list:
>
> d=[]
> car_file = open('worstcars.txt', 'r')
> for line in car_file:
>     d.append(line.strip('\n'))
> print (d)
> car_file.close()
>
> Every line is now an element in list d. The question I have now is how can I make a dictionary out of the list d with the car manufacturer as the key and a tuple containing the year and the model should be the key's value.

Ah, a nice straight-forward text parsing problem!

The question is how to recognize the manufacturer. Is it guaranteed to
be the second blank-delimited word, with the year being the first? If
so, you were almost there with .split().

car_file = open('worstcars.txt', 'r')
# You may want to consider the 'with' statement here - no need to close()
for line in car_file:
    temp = line.split(None, 2)
    if len(temp)==3:
        year, mfg, model = temp
        # Now do something with these three values
        print("Manufacturer: %s  Year: %s  Model: %s"%(mfg,year,model))

That's sorted out the parsing side of things. Do you know how to build
up the dictionary from there?

What happens if there are multiple entries in the file for the same
manufacturer? Do you need to handle that?

ChrisA



More information about the Python-list mailing list