Python-сообщество
можно ли получить ключ по значению в словаре? может есть какая то стандартная функция?
как получить Gorod, зная значение
#2 Май 28, 2012 12:39:31
получить ключ по значению в словаре
Возможно, стоит подумать над изменением логики работы программы. Ну или созданием второго словаря, если операция критична по времени.
#3 Май 28, 2012 12:44:13
получить ключ по значению в словаре
просто я думал может есть стандартные методы.
примерно так я тоже реализовал, переводил в список и смотрел по второму значнию.
сделаю второй словарь наоборот 🙂
#4 Май 28, 2012 12:45:42
получить ключ по значению в словаре
а ещё тогда второй вопрос. нет ли стандартной функци для получения обратного словаря?
ну чтобы опять что-то не ищобретать.
через цикл то сделать смогу, вот так
Отредактировано ilnur (Май 28, 2012 12:47:38)
#5 Май 28, 2012 12:55:26
получить ключ по значению в словаре
Если все значения в словаре хешируемы, тогда:
Отредактировано fata1ex (Май 28, 2012 12:57:54)
#6 Май 28, 2012 13:46:15
получить ключ по значению в словаре
>>>>а ещё тогда второй вопрос. нет ли стандартной функци для получения обратного словаря?
Предположим, у Вас есть словарь
Отредактировано FishHook (Май 28, 2012 13:47:07)
#7 Май 28, 2012 15:14:18
получить ключ по значению в словаре
Непонятно, что делать с дублирующимися значениями. Или тогда делать двухмерный список, или брать только один из дубликатов, или брать все в список.
#8 Май 28, 2012 15:40:58
получить ключ по значению в словаре
asilyator, как бы об этом уже написал FishHook.
Дублирующие значения можно хранить в ключе-кортеже, что может усугубить доступ к значению в новом словаре до O(n), так как потребуется перебор всех ключей, если ключ не найдётся в словаре сам по себе. В любом случае использовать структуры данных надо с умом, понимая, зачем и когда они нужны. Поддерживать актуальными два словаря тоже не самое приятное занятие, поэтому лучше подумать о другой структуре данных или об абстрагировании реализации через свой класс.
Поиск ключа по его значению в словаре Python
В этом посте мы обсудим, как искать ключ по его значению в словаре Python.
1. Использование выражения генератора
Простое решение — использовать генераторное выражение для поиска ключа по его значению в словаре. Вот как будет выглядеть код:
2. Использование обратного словаря
Здесь идея состоит в том, чтобы создать словарь пар значение-ключ. Вы можете использовать zip() для объединения значений и ключей словаря и передачи результата конструктору словаря для получения словаря.
Это предполагает, что в словаре нет двух ключей с одинаковыми значениями, и все значения словаря можно хэшировать. Вы можете упростить код с помощью map() функция:
Это все о поиске ключа по его значению в словаре Python.
Оценить этот пост
Средний рейтинг 5 /5. Подсчет голосов: 20
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования
Python dictionary find a key by value
In this Python tutorial, we will learn about the Python dictionary to find a key by value. Also, we will discuss the below examples:
- Python dictionary find key by max value.
- Python dictionary get Key value by index
- Python dictionary find key using value
- Python dictionary get key value pair
- Python dictionary find key with maximum value
- Python dictionary get key if value exists
Table of Contents
Python dictionary find a key by value
- Here we can see how to get the key by value in Python.
- We can perform this task by various methods, Here is the list of some that we can use.
- By using list.index()
- By using dict.items() method
- By using list comprehension method
By using list.index() method
The index method always returns the index position in a list or dictionary.
Source Code:
Here is the Screenshot of the following given code
By using dict.items() method
This method returns a dictionary view object that displays the list of a dictionary in the key-value pair form.
Example:
Execution:

By using list comprehension method
In Python to get the key with the maximum value, we can use the list comprehension method. This method will help the user to execute each element along with the for loop to iterate each item.
Example:
Output:

Python dictionary find key by max value
- Let us see how to find the key by the maximum value.
- By using the max() function we will find the key with maximum value in Dictionary.
- To do this task first we will initialize a dictionary and assign them a key-value pairs element. Now use a max() function to get the key with maximum value.
Example:
Here is the implementation of the following given code

Another example to get the key with max value
By using the itemgetter() function and operator module we can easily get the key. The itemgetter() function returns an object that collects an item from its operand using the operator module.
Let’s take an example and check how to get the key by using the itemgetter() function.
Here is the Screenshot of the following given code

By using lambda function
In Python, the lambda function did not need any name, they are nameless. They are used to declare a one-line function. In this example, you just need to give the function a value and then provide an expression.
Example:
In this example, we have to check how to find a key with maximum value using the lambda function
Screenshot:

Python dictionary get key value by index
- Let us see how to get a key-value pair by index in the dictionary.
- To perform this task we can use the enumerator method. This is an in-built function in Python that allows the user to check how many iterations have occurred. This method can be used directly for loops and convert them into a list.
- Let’s take an example and check how to get key-value pair by index.
Here is the execution of the following given code

Another example to check how to get key-value index by using dict() method
Source Code:
Here is the Output of the following given code

Python dictionary find key using value
In Python to find a key using the value, we can collect the key from a value by comparing all the values and get the specific key. In this example, we can use dict.items() method.
Example:
Let’s take an example and check how to find a key by using the value.
Here is the Screenshot of the following given code

Python dictionary get key value pair
- To get key-value pair in the dictionary we can easily use the enumerator method.
- This method helps the user to access the named index of the position of the key-value element in the dictionary.
Example:
Here is the implementation of the following given code

Another example to check how to get key value pair
To perform this particular task we can easily use the list comprehension method. This method returns the elements in the form of key-value pairs and it will display the result as tuples of key and value in the list.
Example:
Here is the Screenshot of the following given code

Python dictionary find key with maximum value
To find the key with the maximum value we can easily use the function values() and keys().
Here is the execution of the following given code

Python dictionary get key if value exist
- Let us see how to get a key if the value exists in dictionary.

You may also like reading the following articles.
In this Python tutorial, we have learned about the Python dictionary to find a key by value. Also, we have also discussed the below examples:
- Python dictionary find key by max value.
- Python dictionary get Key value by index
- Python dictionary find key using value
- Python dictionary get key value pair
- Python dictionary find key with maximum value

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.
Поиск ключа по значению в словаре Python:
Довольно новый для Python, все еще борющийся с таким количеством информации.
Вся документация, которую я видел о словарях, объясняет различные способы получения значения с помощью ключа — но я ищу питоновский способ сделать обратное — получить ключ через значение.
Я знаю, что могу перебирать ключи и проверять их значения, пока не найду значение, которое я ищу, а затем возьму ключ, но я ищу прямой маршрут.
4 ответа
Прямого маршрута нет. Это довольно легко с учетом списка, однако;
Если вам нужно сделать это время от времени и не думайте, что стоит его индексировать другим способом, вы можете сделать что-то вроде:
Тогда d.key_with_value будет вести себя скорее как d.get , кроме наоборот.
Вы также можете создать класс, который автоматически индексировал его оба раза. Тогда ключ и значение должны были быть хешируемыми. Вот три способа его реализации:
В двух отдельных dicts с разоблачением некоторых диктоподобных методов; вы могли бы сделать foo.by_key[key] или foo.by_value[value] . (Нет кода, поскольку он более сложный, и я ленивый, и я думаю, что это субоптимально.)
В другой структуре, чтобы вы могли делать d[key] и d.inverse[value] :
В той же структуре, что вы могли бы сделать d[key] и d[value] :
(Заметно отсутствует в этих реализациях a bidict метод update , который будет немного более сложным (но help(dict.update) укажет, что вам нужно будет покрыть). Без update , bidict(<1:2>) не будет делать то, на что он предназначен, и не будет d.update(<1:2>) .)
Также рассмотрите вопрос о том, будет ли более подходящей другая структура данных.