Skip to content Skip to sidebar Skip to footer

Converting Lists To Dictionaries

I want to convert the data below into a dictionary with first column as Id number and rest of the elements as values EDF768, Bill Meyer, 2456, Vet_Parking TY5678, Jane Miller, 898

Solution 1:

Using the csv module:

import csv

d = {}

with open('ParkingData_Part2.txt','r') as fh:
    for line in csv.reader(fh):
        key = line.pop(0)
        d[key] = [item.strip() for item in line]

print d

returns

{'TY5678': ['Jane Miller', '8987', 'AgHort_Parking'], 'GEF123': ['Jill Black', '3456', 'Creche_Parking'], 'EDF768': ['Bill Meyer', '2456', 'Vet_Parking']}

Solution 2:

  for line in data_list:
    key = line[0]
    value = (line[1], line[2], line[3])
    data_dict[key] = value
    dict_list.append(data_dict)
    data_dict = dict() 

On the last line written above, you reset data_dict() to an empty dict before you append it to dict_list. Just switch the two lines around (as shown above).

EDIT To get your output to be a pure dictionary (I'm assuming that all of your keys are unique):

def createNameDict():
    with open("C:\Users\user\Desktop\\ParkingData_Part2.txt","r") as f:
        contents = file.read()
    print contents,"\n"
    data_list = [line.split(",")  for line in contents.split("\n")]
    print data_list, "\n"
    data_dict = {}
    for line in data_list:
        data_dict[line[0]] = line[1:]
    print (data_dict)
    return data_dict

Note that your desired out put is a little ambiguous--the dict example you gave is not properly formatted and will generate a SyntaxError. I believe you mean {'EDF768': ('Bill Meyer', ' 2456', ' Vet_Parking')}


Solution 3:

Try this:

data_dict = {lsitem[0]:lsitem[1:] for lsitem in data_list}

Solution 4:

It is a little awkward the way you are building your dictionaries each time. Just simplify it:

  dict_list = []
  # data_dict = {}  get rid of this
  for line in data_list:
    data_dict = {line[0]: line[1:]}
    dict_list.append(data_dict)

No need to declare a dict and clear it each time.

If what you really want is just a dictionary, do this:

  data_dict = {} 
  for line in data_list:
    data_dict[line[0]] = line[1:]

Solution 5:

For starters, use the csv module, it makes the reading of your file a lot easier:

import csv

def createNameDict():
    data_file = csv.reader(open('ParkingData_Part2.txt', 'rb'))
    return dict(
        (line[0], line[1:]) for line in data_file
    )

Post a Comment for "Converting Lists To Dictionaries"