使用Python中的重复键制作字典
我有以下列表,其中包含重复的具有不同值的汽车注册号。我想将其转换为字典,该字典接受汽车登记号的多个键。
到目前为止,当我尝试将列表转换为字典时,它消除了键之一。如何制作具有重复键的字典?
清单是:
EDF768, Bill Meyer, 2456, Vet_ParkingTY5678, 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, Jenny Meyer, 9987, Vet_Parking
TY5678, Jo King, 8987, AgHort_Parking
JU9807, Mike Green, 3212, Vet_Parking
我试过的代码是:
data_dict = {}data_list = []
def createDictionaryModified(filename):
path = "C:\Users\user\Desktop"
basename = "ParkingData_Part3.txt"
filename = path + "//" + basename
file = open(filename)
contents = file.read()
print contents,"\n"
data_list = [lines.split(",") for lines in contents.split("\n")]
for line in data_list:
regNumber = line[0]
name = line[1]
phoneExtn = line[2]
carpark = line[3].strip()
details = (name,phoneExtn,carpark)
data_dict[regNumber] = details
print data_dict,"\n"
print data_dict.items(),"\n"
print data_dict.values()
回答:
Python字典不支持重复键。一种解决方法是将列表或集合存储在字典中。
一种简单的方法是使用defaultdict
:
from collections import defaultdictdata_dict = defaultdict(list)
你要做的就是更换
data_dict[regNumber] = details
与
data_dict[regNumber].append(details)
你将获得一个列表字典。
以上是 使用Python中的重复键制作字典 的全部内容, 来源链接: utcz.com/qa/407699.html