Creating dictionaries with duplicate keys is not natively supported in Python. Dictionaries, by design, associate unique keys with corresponding values.
However, you can use certain techniques to address this limitation. One approach is to store lists or sets within the dictionary.
Default dictionaries, imported from the collections module, are dictionaries that return a default value for non-existent keys. You can initialize a default dictionary to store lists or sets, allowing you to associate multiple values with the same key:
from collections import defaultdict data_dict = defaultdict(list)
To store values associated with a key, append them to the list within the default dictionary:
regNumber = "ABC234" details = ("Fred Greenside", "2345", "AgHort_Parking") data_dict[regNumber].append(details)
Here is a modified version of your code, using a default dictionary to store registration numbers and their associated data:
from collections import defaultdict data_dict = defaultdict(list) with open("ParkingData_Part3.txt") as file: data_list = [lines.split(",") for lines in file.readlines()] 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].append(details) print(data_dict)
This code will create a dictionary where registration numbers are keys, and each key maps to a list of associated values.
The above is the detailed content of How Can I Store Duplicate Keys in a Python Dictionary?. For more information, please follow other related articles on the PHP Chinese website!