Creating a dictionary from a .txt file

C.T. swilks06 at gmail.com
Sun Mar 31 17:52:50 CEST 2013


Hello,

I'm currently working on a homework problem that requires me to create a dictionary from a .txt file that contains some of the worst cars ever made. The file looks something like this:

1958 MGA Twin Cam
1958 Zunndapp Janus
1961 Amphicar
1961 Corvair
1966 Peel Trident
1970 AMC Gremlin
1970 Triumph Stag
1971 Chrysler Imperial LeBaron Two-Door Hardtop

The car manufacturer should be the key and a tuple containing the year and the model should be the key's value. I tried the following to just get the contents of the file into a list, but only the very last line in the txt file is shown as a list with three elements (ie, ['2004', 'Chevy', 'SSR']) when I print temp.

d={}
car_file = open('worstcars.txt', 'r')
for line in car_file:
    temp = line.split()
print (temp)
car_file.close()

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. Here is a sample of what list d looks like:

['1899 Horsey Horseless', '1909 Ford Model T', '1911 Overland OctoAuto', '2003 Hummer H2', '2004 Chevy SSR']

Any help would be appreciated!



More information about the Python-list mailing list