Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the key from value in a dictionary in Python? [duplicate]

Tags:

python

d[key] = value

but how to get the keys from value?

For example:

a = {"horse": 4, "hot": 10, "hangover": 1, "hugs": 10}
b = 10

print(do_something with 10 to get ["hot", "hugs"])
like image 707
Peter Avatar asked Aug 11 '17 12:08

Peter


People also ask

Can we duplicate key in dictionary Python?

Dictionaries in Python First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.

How do you duplicate a dictionary key?

Use a list in a dictionary to associate more than one value with a key. Create a dictionary with lists as values. Use a list to contain more than one value. Though the key isn't duplicated, multiple values are now assigned to the same key.

Can you get the key of a dictionary by value Python?

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.

How do I extract a dictionary key in Python?

Method 1 : Using List. Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.


1 Answers

You can write a list comprehension to pull out the matching keys.

print([k for k,v in a.items() if v == b])
like image 185
John Kugelman Avatar answered Oct 19 '22 03:10

John Kugelman