On 04/01/2013 07:53 PM, C.T. wrote:
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)

That's rather redundant. Once you've determined that the particular key is already there, why bother with the setdefault() call? Or to put it another way, why bother to test if it's there when you're going to use setdefault to handle the case where it's not?


         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!



--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to