0

我想将下面的数据转换为一个字典,第一列作为 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'}
4

5 回答 5

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']}
于 2012-05-11T05:07:02.313 回答
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')}

于 2012-05-11T04:45:24.850 回答
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:]
于 2012-05-11T04:53:02.453 回答
1

尝试这个:

data_dict = {lsitem[0]:lsitem[1:] for lsitem in data_list}
于 2012-05-11T04:57:56.360 回答
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
    )
于 2012-05-11T05:02:08.727 回答