Creating a dictionary from a .txt file

Dave Angel davea at davea.name
Mon Apr 1 20:12:31 EDT 2013


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



More information about the Python-list mailing list