Creating a dictionary from a .txt file

Terry Jan Reedy tjreedy at udel.edu
Sun Mar 31 15:04:54 EDT 2013


On 3/31/2013 11:52 AM, C.T. wrote:
> 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()

If all makers are one word (Austen-Martin would be ok, and if the file 
is otherwise consistently year maker model words, then adding 
'maxsplit=3' to the split call would be all the parsing you need.






More information about the Python-list mailing list