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()
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.
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.
You can change the behavior of the built in types in Python. For your case it's really easy to create a dict subclass that will store duplicated values in lists under the same key automatically:
class Dictlist(dict): def __setitem__(self, key, value): try: self[key] except KeyError: super(Dictlist, self).__setitem__(key, []) self[key].append(value)
Output example:
>>> 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]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With