python字典重复的键,使用Python中的重复键制作字典

I have the following list which contains duplicate car registration numbers with different values. I want to convert it into a dictionary which accepts this multiple keys of car registration numbers.

So far when I try to convert list to dictionary it eliminates one of the keys. How do I make a dictionary with duplicate keys?

The list is:

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, Jenny Meyer, 9987, Vet_Parking

TY5678, Jo King, 8987, AgHort_Parking

JU9807, Mike Green, 3212, Vet_Parking

The code I have tried is:

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 dictionaries don't support duplicate keys. One way around is to store lists or sets inside the dictionary.

One easy way to achieve this is by using defaultdict:

from collections import defaultdict

data_dict = defaultdict(list)

All you have to do is replace

data_dict[regNumber] = details

with

data_dict[regNumber].append(details)

and you'll get a dictionary of lists.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值