Creating a dictionary from a .txt file
C.T.
swilks06 at gmail.com
Mon Apr 1 19:53:53 EDT 2013
Thanks for all the help everyone! After I manually edited the txt file, this is what I came up with:
car_dict = {}
car_file = open('cars.txt', 'r')
for line in car_file:
temp = line.strip().split(None, 2)
temp2 = line.strip().split('\t')
if len(temp)==3:
year, manufacturer, model = temp[0] ,temp2[0][5:], temp2[1]
value = (year, model)
if manufacturer in car_dict:
car_dict.setdefault(manufacturer,[]).append(value)
else:
car_dict[manufacturer] = [value]
elif len(temp)==2:
year, manufacturer, model = temp[0], 'Unknown' , temp2[1]
value = (year, model)
if manufacturer in car_dict:
car_dict.setdefault(manufacturer,[]).append(value)
else:
car_dict[manufacturer] = [value]
car_file.close()
print (car_dict)
It may not be the most pythonic way of doing this, but it works for me. I am learning python, and this problem was problem the most challenging so far. Thank you all, again!
More information about the Python-list
mailing list