将列表转换为字典

时间:2012-05-11 04:41:54

标签: python

我想将下面的数据转换为字典,第一列为Id编号,其余元素为值

EDF768, Bill Meyer, 2456, Vet_Parking

TY5678, Jane Miller, 8987, AgHort_Parking

GEF123, Jill Black, 3456, Creche_Parking

到目前为止,我已打开文件并将数据转换为列表。但我无法将其转换为字典,因为它表明等式太长了。

def createNameDict():
      file = open("C:\Users\user\Desktop\\ParkingData_Part2.txt","rt")
      contents = file.read()
      print contents,"\n"
      data_list = [line.split(",")  for line in contents.split("\n")]
      print data_list, "\n"
      dict_list = []
      data_dict = {}
      for line in data_list:
        key = line[0]
        value = (line[1], line[2], line[3])
        data_dict[key] = value
        data_dict = dict()

        dict_list.append(data_dict)
        # start dictionary over
        #print data_dict
      print (data_list)


      file.close()

我的输出是:

[['EDF768', ' Bill Meyer', ' 2456', ' Vet_Parking'], 
['TY5678', ' Jane Miller', ' 8987', ' AgHort_Parking'], 
['GEF123', ' Jill Black', ' 3456', ' Creche_Parking'], 
['ABC234', ' Fred Greenside', ' 2345', ' AgHort_Parking'], 
['GH7682', ' Clara Hill', ' 7689', ' AgHort_Parking'], 
['JU9807', ' Jacky Blair', ' 7867', ' Vet_Parking'], 
['KLOI98', ' Martha Miller', ' 4563', ' Vet_Parking'], 
['ADF645', ' Cloe Freckle', ' 6789', ' Vet_Parking'], 
['DF7800', ' Jacko Frizzle', ' 4532', ' Creche_Parking'], 
['WER546', ' Olga Grey', ' 9898', ' Creche_Parking'], 
['HUY768', ' Wilbur Matty', ' 8912', ' Creche_Parking']] 

有人可以给我提示将上面的列表转换为字典,如:

{'EDF768': ' Bill Meyer', ' 2456', ' Vet_Parking'}

5 个答案:

答案 0 :(得分:7)

使用csv模块:

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

返回

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

答案 1 :(得分:1)

  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() 

在上面写的最后一行,您将data_dict()重置为空的字典,然后再将附加到dict_list。只需切换两条线(如上图所示)。

修改 要使你的输出成为一个纯字典(我假设你的所有键都是唯一的):

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

请注意,您所需的输出有点模棱两可 - 您提供的dict示例格式不正确,并会生成SyntaxError。我相信你的意思是{'EDF768': ('Bill Meyer', ' 2456', ' Vet_Parking')}

答案 2 :(得分:1)

每次构建词典的方式都有点尴尬。只是简化它:

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

无需每次都宣布一个词典并清除它。

如果您真正想要的只是字典,请执行以下操作:

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

答案 3 :(得分:1)

试试这个:

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

答案 4 :(得分:1)

首先,使用csv模块,它可以更轻松地读取文件:

import csv

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