- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Get key with maximum value in Dictionary in Python
- How to get a value for a given key from a Python dictionary?
- Accessing Key-value in a Python Dictionary
- Get key from value in JavaScript
- What is possible key/value delimiter in Python dictionary?
- Add a key value pair to dictionary in Python
- Get the number of key/value pairs in the Dictionary in C#
- How to extract subset of key-value pairs from Python dictionary object?
- Add key-value pair in C# Dictionary
- Python – Extract Key’s Value, if Key Present in List and Dictionary
- Python - Ways to remove a key from dictionary
- How to update the value of a key in a dictionary in Python?
- Python program to get maximum of each key Dictionary List
- How to remove a key from a python dictionary?
- Python - Get items in sorted order from given dictionary

Advertisements