Home > Backend Development > Python Tutorial > How Can I Store Duplicate Keys in a Python Dictionary?

How Can I Store Duplicate Keys in a Python Dictionary?

Susan Sarandon
Release: 2024-12-21 09:42:15
Original
446 people have browsed it

How Can I Store Duplicate Keys in a Python Dictionary?

Storing Duplicate Keys in Python Dictionaries

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.

Using Default Dictionaries

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)
Copy after login

Manipulating Default Dictionary Items

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)
Copy after login

Example Code

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template