already been answered, but since several people mentioned reversing the dictionary, here’s how you do it in one line (assuming 1:1 mapping) and some various perf data:
python 2.6:
reversedict = dict([(value, key) for key, value in mydict.iteritems()])
2.7+:
reversedict = {value:key for key, value in mydict.iteritems()}
if you think it’s not 1:1, you can still create a reasonable reverse mapping with a couple lines:
reversedict = defaultdict(list)
[reversedict[value].append(key) for key, value in mydict.iteritems()]
how slow is this: slower than a simple search, but not nearly as slow as you’d think — on a ‘straight’ 100000 entry dictionary, a ‘fast’ search (i.e. looking for a value that should be early in the keys) was about 10x faster than reversing the entire dictionary, and a ‘slow’ search (towards the end) about 4-5x faster. So after at most about 10 lookups, it’s paid for itself.
the second version (with lists per item) takes about 2.5x as long as the simple version.
largedict = dict((x,x) for x in range(100000))
# Should be slow, has to search 90000 entries before it finds it
In [26]: %timeit largedict.keys()[largedict.values().index(90000)]
100 loops, best of 3: 4.81 ms per loop
# Should be fast, has to only search 9 entries to find it.
In [27]: %timeit largedict.keys()[largedict.values().index(9)]
100 loops, best of 3: 2.94 ms per loop
# How about using iterkeys() instead of keys()?
# These are faster, because you don't have to create the entire keys array.
# You DO have to create the entire values array - more on that later.
In [31]: %timeit islice(largedict.iterkeys(), largedict.values().index(90000))
100 loops, best of 3: 3.38 ms per loop
In [32]: %timeit islice(largedict.iterkeys(), largedict.values().index(9))
1000 loops, best of 3: 1.48 ms per loop
In [24]: %timeit reversedict = dict([(value, key) for key, value in largedict.iteritems()])
10 loops, best of 3: 22.9 ms per loop
In [23]: %%timeit
....: reversedict = defaultdict(list)
....: [reversedict[value].append(key) for key, value in largedict.iteritems()]
....:
10 loops, best of 3: 53.6 ms per loop
Also had some interesting results with ifilter. Theoretically, ifilter should be faster, in that we can use itervalues() and possibly not have to create/go through the entire values list. In practice, the results were… odd…
In [72]: %%timeit
....: myf = ifilter(lambda x: x[1] == 90000, largedict.iteritems())
....: myf.next()[0]
....:
100 loops, best of 3: 15.1 ms per loop
In [73]: %%timeit
....: myf = ifilter(lambda x: x[1] == 9, largedict.iteritems())
....: myf.next()[0]
....:
100000 loops, best of 3: 2.36 us per loop
So, for small offsets, it was dramatically faster than any previous version (2.36 *u*S vs. a minimum of 1.48 *m*S for previous cases). However, for large offsets near the end of the list, it was dramatically slower (15.1ms vs. the same 1.48mS). The small savings at the low end is not worth the cost at the high end, imho.
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
- 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:
to_dictionary ={"Bulgaria":450, "Australia":610, "Canada":916}
new_ke_lis = list(to_dictionary.keys())
new_val = list(to_dictionary.values())
new_pos = new_val.index(610) # value from dictionary
print("Get a key by value:",new_ke_lis[new_pos])
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:
my_dict={"a":6,"z":9,"f":17,"l":10}
for key,value in my_dict.items():
if value==9:
print("key by value:",key)
Execution:
Read: How to Create a Dictionary from one list in Python
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:
new_dictionary={"m":45,"v":19,"q":87,"w":60}
t={s for s in new_dictionary if new_dictionary[s]==19}
print("key by value:",t)
Output:
Read: Python convert dictionary to list
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:
new_dict={"x":35,"q":29,"e":97,"w":60}
new_ke = max(new_dict, key=new_dict.get)
print("To get Key maxvalue:",new_ke)
Here is the implementation of the following given code
Read: How to create a list of dictionary keys in python
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.
Source Code:
import operator
my_dict1 = {"Bulgaria": 92, "Cuba": 81, "Cyprus": 96}
new_max_key = max(my_dict1.items(), key = operator.itemgetter(1))[0]
print("key with highest value:n",new_max_key)
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
my_dict2 = {"Egypt": 129, "Denmark": 95, "Greece": 196}
ma_value = max(my_dict2, key= lambda i: my_dict2[i])
print(ma_value)
Screenshot:
Read: Python dictionary remove
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.
my_new_dict = {'c' : 43, 'i' : 61, 'x' : 93, 'l' : 54}
get_key = 'i'
new_search_key='l'
new_var = list(my_new_dict.items())
output = [ab for ab, new_key in enumerate(new_var) if new_key[0] == get_key]
result2 = [ab for ab, new_key in enumerate(new_var) if new_key[0] == new_search_key]
print("Get index value of key : ",output)
print("Get index value of key : ",result2)
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:
dict1 = {'JOhn' : 29, 'POtter' : 18, 'Chris' : 17, 'hemsworth' : 14}
ind_lis = list(dict1)
new_key = ind_lis[1]
print("Get key-value by index:",new_key)
Here is the Output of the following given code
Read: Python dictionary length
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.
from typing import TextIO
def new_ke(val):
for k, new_va in to_dictionary.items():
if val == new_va:
return k
return
to_dictionary ={"Australia":56, "China":72, "Turkey":93}
print("Key exist in dictionary:",new_ke(72))
print("key doesnot contain in dictionary:",new_ke(48))
Here is the Screenshot of the following given code
Read: Python Dictionary index
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:
dictionary1 = {"Iran" : 37, "Iraq" : 19, "Ireland" : 64}
for x in enumerate(dictionary1.items()):
print("key-value pair in dictionary:",x)
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:
you_dictionary = {"Maldives" : 34, "Mexico" : 159, "Portugal" : 287}
print ("key-value pairs are : ")
print([(m, you_dictionary[m]) for m in you_dictionary])
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().
Source Code:
to_dict2 = {'Zimbabwe':689, 'Ukraine':143, 'Italy':189}
new_value = list(to_dict2.values())
new_key = list(to_dict2.keys())
print(new_key[new_value.index(max(new_value))])
Here is the execution of the following given code
Read: Python dictionary initialize
Python dictionary get key if value exist
- Let us see how to get a key if the value exists in dictionary.
Source Code:
from typing import TextIO
def exe_ke(val):
for x, new_va in your_dict.items():
if val == new_va:
return x
return
your_dict ={"m":124, "s":149, "u":98}
print("Value exist in dictionary:",exe_ke(149))
print("value doesnot exist in dictionary:",exe_ke(456))
Execution
You may also like reading the following articles.
- Python dictionary filter
- Python Dictionary sort
- Python dictionary comprehension
- Python dictionary contains
- Python dictionary pop
- Python dictionary of lists
- Get all values from a dictionary Python
- Python creates a dictionary from two lists
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 мы можем получить значения, присутствующие в словаре, по их ключам. Для этого используется синтаксис dict_name[key_name]
. Но мы не можем таким же образом получить ключ по значению.
В этой статье мы рассмотрим способы, с помощью которых мы можем получить ключ заданного значения в словаре.
Как получить ключ из пары ключ-значение путем перебора элементов словаря
Это самый простой способ извлечь ключ по значению. Мы проверяем каждую пару ключ-значение, чтобы найти ключ, связанный с текущим значением.
Для этой задачи мы будем использовать метод items()
. Этот словарный метод возвращает список кортежей, содержащих пары ключ-значение. В полученном списке мы проверим каждый кортеж, чтобы найти ключ, связанный с нашим значением.
myDict = {"name": "PythonTurbo", "acronym": "PT"} print("Dictionary is:") print(myDict) dict_items = myDict.items() print("Given value is:") myValue = "PT" print(myValue) print("Associated Key is:") for key, value in dict_items: if value == myValue: print(key)
Результат:
Dictionary is: {'name': 'PythonTurbo', 'acronym': 'PT'} Given value is: PT Associated Key is: acronym
Мы создали список элементов в myDict
с помощью myDict.items()
, а затем проверили каждый элемент в списке, чтобы найти ключ для нашего значения.
Как получить ключ по значению с помощью списков
Мы можем создать отдельные списки из ключей и значений, а затем найти ключ нужного значения с помощью метода index()
.
Для этой задачи мы сначала создадим список ключей, имеющихся в словаре, используя метод keys()
. Затем создадим список значений, используя метод values()
. После этого мы получим индекс нужного значения из списка значений с помощью метода index()
.
Мы знаем, что список ключей имеет тот же порядок ключей, что и значения в списке значений. Поэтому индекс значения в списке значений будет таким же, как и индекс связанного с ним ключа в списке ключей. Таким образом, найдя индекс значения в списке значений, мы можем найти ключ в списке ключей по тому же индексу.
Это можно сделать следующим образом:
myDict = {"name": "PythonTurbo", "acronym": "PT"} print("Dictionary is:") print(myDict) dict_keys = list(myDict.keys()) dict_values = list(myDict.values()) print("Given value is:") myValue = "PT" print(myValue) val_index = dict_values.index(myValue) print("Associated key is:") myKey = dict_keys[val_index] print(myKey)
Выходные данные:
Dictionary is: {'name': 'PythonTurbo', 'acronym': 'PT'} Given value is: PT Associated key is: acronym
Как получить ключ по значению с помощью list comprehension
Для получения ключа, связанного с заданным значением, вместо метода index()
можно использовать представление списка. О представлениях списков вы можете почитать в статье “List comprehensions и другие comprehensions в Python”.
Чтобы найти ключ, мы создадим список ключей, значения которых равны заданному значению:
myDict = {"name": "PythonTurbo", "acronym": "PT"} print("Dictionary is:") print(myDict) dict_items = myDict.items() print("Given value is:") myValue = "PT" print(myValue) print("Associated key is:") myKey = [key for key, value in dict_items if value == myValue] print(myKey)
Результат:
Dictionary is: {'name': 'PythonTurbo', 'acronym': 'PT'} Given value is: PT Associated key is: ['acronym']
Заключение
В этой статье мы рассмотрели три способа получить из словаря Python ключ по значению: с помощью list comprehension
, метода items()
и метода index()
.
Перевод статьи Aditya Raj “Get key from value in dictionary“
Let’s see how to get the key by value in Python Dictionary.
Example: One-Liner code
Python3
my_dict
=
{
"Java"
:
100
,
"Python"
:
112
,
"C"
:
11
}
print
(
"One line Code Key value: "
,
list
(my_dict.keys())
[
list
(my_dict.values()).index(
100
)])
Output:
Java
Extract Key from Python Dictionary using Value
Method 1: Get the key by value using list comprehension
A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list to get the key from a value in Dictionary.
Python3
dic
=
{
"geeks"
:
"A"
,
"for"
:
"B"
,
"geeks"
:
"C"
}
value
=
{i
for
i
in
dic
if
dic[i]
=
=
"B"
}
print
(
"key by value:"
,value)
Output:
key by value: {'for'}
Time Complexity: O(N)
Auxiliary Space: O(1)
Method 2: Get the key by value using a list.index()
The index() method returns the index of the corresponding value in a list. The approach used here is to find two separate lists of keys and values. Then fetch the key using the position of the value in the val_list. As key at any position N in key_list will have a corresponding value at position N in val_list.
Python3
my_dict
=
{
"java"
:
100
,
"python"
:
112
,
"c"
:
11
}
key_list
=
list
(my_dict.keys())
val_list
=
list
(my_dict.values())
position
=
val_list.index(
100
)
print
(key_list[position])
Output:
java
Time complexity: O(1)
Auxiliary space: O(1)
Method 3: Get the key by value using dict.item()
We can also fetch the key from a value by matching all the values using the dict.item() and then printing the corresponding key to the given value.
Python3
def
get_key(val):
for
key, value
in
my_dict.items():
if
val
=
=
value:
return
key
return
"key doesn't exist"
my_dict
=
{
"Java"
:
100
,
"Python"
:
112
,
"C"
:
11
}
print
(get_key(
100
))
print
(get_key(
11
))
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(1), as the space used by the function does not depend on the size of the input dictionary.
Method 4: Using lambda and filter()
Here is an example of using the filter() function to get the key corresponding to a value in a dictionary:
Python3
my_dict
=
{
"Java"
:
100
,
"Python"
:
112
,
"C"
:
11
}
key
=
list
(
filter
(
lambda
x: my_dict[x]
=
=
100
, my_dict))[
0
]
print
(key)
In this example, the filter() function is used to create a list of keys from my_dict where the value is equal to 100. The resulting list is then indexed at position 0 to get the first element, which is the key corresponding to the value 100.
Time complexity: O(n), as the filter() function needs to iterate through the entire dictionary to create the list of keys.
Auxiliary space is O(n), as the list of keys created by filter() has a size equal to the number of elements in the dictionary.
METHOD 5:Using items method
This code finds the key of a given value in a dictionary by using a list comprehension to iterate over the items in the dictionary and check if the value matches the given value. If a key is found, it is added to a list, and the first element of the list is printed as the key for the given value. If the value is not found in the dictionary, a message is printed indicating that it was not found.
Steps:
- Use the items method of the dictionary to loop through each key-value pair in my_dict.
- Check if the value associated with the current key is equal to the given value.
- If it is equal, append the current key to a list of keys.
- If the loop completes without finding a matching value, print a message indicating that the value was not found.
- If a matching key was found, print the first key in the list.
Python3
my_dict
=
{
"Java"
:
100
,
"Python"
:
112
,
"C"
:
11
}
value
=
112
key_list
=
[key
for
key, val
in
my_dict.items()
if
val
=
=
value]
if
len
(key_list) >
0
:
print
(
"The key for the value"
, value,
"is"
, key_list[
0
])
else
:
print
(
"Value not found in dictionary"
)
Output
The key for the value 112 is Python
Time complexity: O(N), where n is the number of key-value pairs in the dictionary.
Auxiliary Space: O(K), where k is the number of keys that match the given value.
METHOD 6:Using re module
The program uses the re module in Python to find the key in a dictionary that corresponds to a given value. It creates a regular expression pattern that matches the value surrounded by word boundaries, then uses the next() function to iterate over the items in the dictionary and search for a value that matches the pattern. If a match is found, the program returns the corresponding key.
ALGORITHM:
- Create a regular expression pattern that matches the value we’re looking for, surrounded by word boundaries.
- Use the next() function to iterate over the items in the dictionary, searching for a value that matches the pattern.
- If a match is found, return the corresponding key. Otherwise, return None.
Python3
import
re
my_dict
=
{
"Java"
:
100
,
"Python"
:
112
,
"C"
:
11
}
value
=
100
pattern
=
re.
compile
(r
'b'
+
str
(value)
+
r
'b'
)
key
=
next
((k
for
k, v
in
my_dict.items()
if
pattern.search(
str
(v))),
None
)
print
(key)
Time complexity: O(N), Creating the regular expression pattern takes O(1) time. Searching for a value that matches the pattern in each dictionary item takes O(n) time in the worst case, where n is the number of items in the dictionary. The next() function and the if statement each takes O(1) time. Therefore, the overall time complexity of the program is O(n).
Auxiliary Space: O(1), The regular expression pattern, and the key variable each require O(1) space. The pattern variable and the generator expression inside the next() function both require O(1) space. The k and v variables used in the generator expression do not require additional space, as they are created as part of the iteration. Therefore, the overall space complexity of the program is O(1).
Last Updated :
04 May, 2023
Like Article
Save Article
К примеру есть строка и есть словарь. В словаре есть ключи и их значения. Что бы вернуть ключ, нужно —
s3 = 'abcd'
d = {a:'а', b:'б', c:'ц', d:'д'}
for smbl in s3:
if smbl in d.keys():
print(d[smbl], end='')
Таким макаром я могу получить ключ, но как получить значение по ключу?
Если я делаю так
for smbl in s3:
if smbl in d.values:
print(d[smbl], end='')
То получаю KeyError
-
Вопрос заданболее трёх лет назад
-
29713 просмотров
Пригласить эксперта
keys = "abcd"
dd = {"a": 1, "b": 2, "c": 3, "d": 4}
for key in keys:
print(dd[key])
А теперь правильный вариант:
In [1]: e = 'abcd'
In [2]: r = 'абцд'
In [3]: m = str.maketrans(e,r)
In [4]: 'abbcc'.translate(m)
Out[4]: 'аббцц'
In [5]: m = str.maketrans(r,e)
In [6]: 'цааб'.translate(m)
Out[6]: 'caab'
d = {"a": 1, "b": 2, "c": 3, "d": 4}
rd = {}
for k, v in d.items():
rd[v] = rd.get(v, []) + [k]
меняем местами ключи со значениями.
на случай повторяющихся значений, бывшие ключи в новом словаре в виде списка.
-
Показать ещё
Загружается…
30 мая 2023, в 00:34
1000 руб./за проект
29 мая 2023, в 23:21
2000 руб./за проект
29 мая 2023, в 22:30
10000 руб./за проект