

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- 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
- How to extract subset of key-value pairs from Python dictionary object?
- Get the number of key/value pairs in the Dictionary in C#
- Add key-value pair in C# Dictionary
- Python - Ways to remove a key from dictionary
- Python – Extract Key’s Value, if Key Present in List and Dictionary
- How to remove a key from a python dictionary?
- Python program to get maximum of each key Dictionary List
- Get value for key from nested JSON object in JavaScript
- How to update the value of a key in a dictionary in Python?
Advertisements