Alex Rivera | Logout

How can one make a dictionary with duplicate keys in Python?

Asked 2012-05-19T11:37:28.937
118

I have a text file which contains duplicate car registration numbers with different values, like so:

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

I want to create a dictionary from this data, which uses the registration numbers (first column) as keys and the data from the rest of the line for values.

I wrote this code:

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 problem is that the data file contains duplicate values for the registration numbers. When I try to store them in the same dictionary with data_dict[regNumber] = details, the old value is overwritten.

How do I make a dictionary with duplicate keys?


Sometimes people want to &qu

Edit
Report

2 Answers

170

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.

answered 2012-05-19T11:41:15.263
9

You can't have a dict with duplicate keys for definition! Instead you can use a single key and, as the value, a list of elements that had that key.

So you can follow these steps:

  1. See if the current element's key (of your initial set) is in the final dict. If it is, go to step 3
  2. Update dict with key
  3. Append the new value to the dict[key] list
  4. Repeat [1-3]
answered 2012-05-19T11:40:59.913

Your Answer