在python中制作带有重复键的字典我有以下清单,其中包含不同值的重复汽车登记号码。我想把它转换成一本字典,它接受这个多键的汽车登记号码。到目前为止,当我试图将列表转换为字典时,它删除了其中一个键。有人能告诉我如何用重复的键制作字典吗?列表是:EDF768, Bill Meyer, 2456, Vet_ParkingTY5678, Jane Miller, 8987, AgHort_ParkingGEF123, Jill Black, 3456, Creche_ParkingABC234, Fred Greenside, 2345, AgHort_ParkingGH7682, Clara Hill, 7689, AgHort_ParkingJU9807, Jacky Blair, 7867, Vet_ParkingKLOI98, Martha Miller, 4563, Vet_ParkingADF645, Cloe Freckle, 6789, Vet_ParkingDF7800, Jacko Frizzle, 4532, Creche_ParkingWER546, Olga Grey, 9898, Creche_ParkingHUY768, Wilbur Matty, 8912, Creche_ParkingEDF768, Jenny Meyer, 9987, Vet_ParkingTY5678, Jo King, 8987, AgHort_ParkingJU9807, 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()
3 回答
MYYA
TA贡献1868条经验 获得超4个赞
defaultdict
:
from collections import defaultdict data_dict = defaultdict(list)
data_dict[regNumber] = details
data_dict[regNumber].append(details)
蛊毒传说
TA贡献1895条经验 获得超3个赞
class Dictlist(dict): def __setitem__(self, key, value): try: self[key] except KeyError: super(Dictlist, self).__setitem__(key, []) self[key].append(value)
>>> d = dictlist.Dictlist()>>> d['test'] = 1>>> d['test'] = 2>>> d['test'] = 3>>> d{'test': [1, 2, 3]}>>> d['other'] = 100 >>> d{'test': [1, 2, 3], 'other': [100]}
添加回答
举报
0/150
提交
取消