
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Key from Value in Dictionary in Python
Python dictionary contains key value pairs. In this article we aim to get the value of the key when we know the value of the element. Ideally the values extracted from the key but here we are doing the reverse.
With index and values
We use the index and values functions of dictionary collection to achieve this. We design a list to first get the values and then the keys from it.
Example
dictA = {"Mon": 3, "Tue": 11, "Wed": 8} # list of keys and values keys = list(dictA.keys()) vals = list(dictA.values()) print(keys[vals.index(11)]) print(keys[vals.index(8)]) # in one-line print(list(dictA.keys())[list(dictA.values()).index(3)])
Output
Running the above code gives us the following result −
Tue Wed Mon
With items
We design a function to take the value as input and compare it with the value present in each item of the dictionary. If the value matches the key is returned.
Example
dictA = {"Mon": 3, "Tue": 11, "Wed": 8} def GetKey(val): for key, value in dictA.items(): if val == value: return key return "key doesn't exist" print(GetKey(11)) print(GetKey(3)) print(GetKey(10))
Output
Running the above code gives us the following result −
Tue Mon key doesn't exist
Advertisements