Python словарь повторяющимися ключами

Как создать словарь с повторяющимися значениями ключей?

Мне нужно создать функцию, которая принимает такой список и дает словарь, в котором имя, фамилия и возраст используются в качестве ключа, а имя собаки является значением. Для этого конкретного списка ответ:

Я пытался создать список ключей, создать список значений, а затем попытаться как-то поместить их в словарь

q=[] for i in pets: q.append(tuple(i[-3:])) 

Этот шаг дает мне список ключей:

[('John', 'Malkovic', 22), ('Jake', 'Smirnoff', 18), ('Simon', 'Ng', 32), ('Martha', 'Black', 73), ('Simon', 'Ng', 32)] 

Затем создаю список значений:

b=[] for i in pets: b.append(i[0]) 
['Fido', 'Butch', 'Zooma', 'Chase', 'Rocky'] 

А затем я пытаюсь заполнить словарь, используя эти два списка:

Но я не получаю то, что мне нужно:

Во-первых, этот метод не позволяет мне поставить два значения для одного ключа (в этом случае мне нужно связать значения «Zooma» и «Rocky» с ключом «(» Simon «,» Ng «, 32)»), а во-вторых, он пропускает значение, если список, содержащий ключи, имеет два одинаковых ключа (в данном случае он имеет два экземпляра («Simon», «Ng», 32)). Как мне создать такой словарь?

3 ответа

Что происходит, так это то, что q и b объединяются в пары, а затем каждая запись рассматривается как пара ключ / значение для словаря. Если q имеет повторяющиеся записи, это означает, что один и тот же ключ будет установлен дважды, а его значение будет перезаписано (не пропущено).

Читайте также:  Text decoration css примеры

Вы хотите, чтобы ваши значения были списками значений, но приведенная выше команда установит их как прямые значения (обратите внимание на ваш собственный пример, что домашних животных нет в списках).

Одно из решений, которое следует вашей логике до последнего шага, — использовать defaultdict списков:

from collections import defaultdict # . d = defaultdict(list) for person, pet in zip(q, b): d[person].append(pet) 

defaultdict позволяет избежать создания нового списка для каждого значения и создает пустой список для добавления для каждого нового ключа, просто добавляя к списку существующих ключей.

Однако более простой подход — просто создать словарь за один раз:

from collections import defaultdict pets = [("Fido", "John", "Malkovic", 22), ("Butch", "Jake", "Smirnoff", 18), ("Zooma", "Simon", "Ng", 32), ("Chase", "Martha", "Black", 73), ("Rocky", "Simon", "Ng", 32)] d = defaultdict(list) for pet, first, last, age in pets: d[(first, last, age)].append(pet) 

Или, если вам действительно не нужен defaultdict :

d = <> for pet, first, last, age in pets: key = (first, last, age) if key not in d: dPython словарь повторяющимися ключами = [] dPython словарь повторяющимися ключами.append(pet) 
pets = [("Fido", "John", "Malkovic", 22), ("Butch", "Jake", "Smirnoff", 18), ("Zooma", "Simon", "Ng", 32), ("Chase", "Martha", "Black", 73), ("Rocky", "Simon", "Ng", 32)] data = [ for item in pets] res = dict() for dict in data: for list in dict: if list in res: res[list] += (dict[list]) else: res[list] = dict[list] print(res) 

Вы можете использовать defaultdict(list) — это автоматически создает новый список, когда владелец не является ключом словаря, и добавляет к нему, если они уже являются ключом:

from collections import defaultdict d = defaultdict(list) for row in pets: d[row[1:]].append(row[0]) 

Источник

Can a dictionary have duplicate keys in Python?

In this article, we will find out whether a dictionary has duplicate keys or not in Python.

The straight answer is NO. You can not have duplicate keys in a dictionary in Python. But we can have a similar effect as keeping duplicate keys in dictionary. We need to understand the reason behind this question and how we can achieve duplicate keys in Python.

Why you can not have duplicate keys in a dictionary?

You can not have duplicate keys in Python, but you can have multiple values associated with a key in Python. If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary. The dictionary can not have the same keys, but we can achieve a similar effect by keeping multiple values for a key in the dictionary.

Let’s understand with an example,

Suppose we have a dictionary of names and phone numbers,

Frequently Asked:

# Dictionary of names and phone numbers phone_details =

As of now, each name (key) has a phone number associated with it. But suppose “John” has two more phone numbers, and we want to add those too in the dictionary. As the Key ‘John’ already exist in the dictionary, so if we try adding two more key-value pair with the same key like this,

phone_details['John'] = 111223 phone_details['John'] = 333444

OR

phone_details.update(< 'John' : 111223>) phone_details.update(< 'John' : 333444>)

It will update the value of the existing key ‘John’ i.e.

Mathew - 212323 Ritika - 334455 John - 333444

To avoid this kind of problem, we can assign multiple values to a single key. Like this,

Mathew - 212323 Ritika - 334455 John - [345323, 111223, 333444]

Adding multiple values for a key in dictionary in Python

Instead of inserting a duplicate key, we can change the type of value to the list and assign more values to it.

def add_value(dict_obj, key, value): ''' Adds a key-value pair to the dictionary. If the key already exists in the dictionary, it will associate multiple values with that key instead of overwritting its value''' if key not in dict_obj: dict_objPython словарь повторяющимися ключами = value elif isinstance(dict_objPython словарь повторяющимися ключами, list): dict_objPython словарь повторяющимися ключами.append(value) else: dict_objPython словарь повторяющимися ключами = [dict_objPython словарь повторяющимися ключами, value] # Dictionary of names and phone numbers phone_details = < 'Mathew': 212323, 'Ritika': 334455, 'John' : 345323 ># Append a value to the existing key add_value(phone_details, 'John', 111223) # Append a value to the existing key add_value(phone_details, 'John', 333444) for key, value in phone_details.items(): print(key, ' - ', value)
Mathew - 212323 Ritika - 334455 John - [345323, 111223, 333444]

Here we created a function add_value() that adds a key-value pair to the dictionary. If the key already exists in the dictionary, it will associate multiple values with that key instead of overwritting its value. It follows this logic.

  • If the key does not exist, then add the key-value pair.
  • If key exists in dictionary and type of value is not list. Then create a temporary list and add old and new values to it. Then assign the list object as the value for the key in dictionary.
  • If key exists in dictionary and type of value is a list. Then add new value to the list.

So, this is how we can have duplicate keys in a dictionary, i.e., by adding multiple values for the same key in a dictionary in Python.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

сделать словарь с дубликатами ключей в python

У меня есть следующий список, который содержит повторяющиеся регистрационные номера автомобилей с разными значениями. Я хочу преобразовать его в словарь, который принимает эти несколько ключей регистрационных номеров автомобилей. Пока я пытаюсь преобразовать список в словарь, он устраняет один из ключей. Может кто-нибудь показать мне, как сделать словарь с дублирующимися ключами Список:

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 
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

У меня есть следующий список, который содержит повторяющиеся регистрационные номера автомобилей с разными значениями. Я хочу преобразовать его в словарь, который принимает несколько ключей регистрационных номеров автомобилей. Пока что, когда я пытаюсь преобразовать список в словарь, он удаляет один из ключей. Как сделать словарь с повторяющимися ключами? Список такой:

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 
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() 

Источник

Оцените статью