
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
Keys Associated with Values in Dictionary in Python
When it is required to find the keys associated with specific values in a dictionary, the ‘index’ method can be used.
Below is the demonstration of the same −
Example
my_dict ={"Hi":100, "there":121, "Mark":189} print("The dictionary is :") print(my_dict) dict_key = list(my_dict.keys()) print("The keys in the dictionary are :") print(dict_key) dict_val = list(my_dict.values()) print("The values in the dictionary are :") print(dict_val) my_position = dict_val.index(100) print("The value at position 100 is : ") print(dict_key[my_position]) my_position = dict_val.index(189) print("The value at position 189 is") print(dict_key[my_position])
Output
The dictionary is : {'Hi': 100, 'there': 121, 'Mark': 189} The keys in the dictionary are : ['Hi', 'there', 'Mark'] The values in the dictionary are : [100, 121, 189] The value at position 100 is : Hi The value at position 189 is Mark
Explanation
A dictionary is defined, and is displayed on the console.
The keys of the dictionary are accessed using the ‘.keys’ and is converted into a list.
This is assigned to a variable
The values of the dictionary are accessed using the ‘.values’ and is converted into a list.
This is assigned to another variable.
The values index is accessed and assigned to a variable.
This is displayed as the output.
Advertisements