Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Keys associated with Values in Dictionary in Python
When you need to find the keys associated with specific values in a dictionary, Python provides several approaches. The most common method is using the index() method with dictionary keys and values converted to lists.
Using index() Method
This approach converts dictionary keys and values to lists, then uses index() to find the position ?
my_dict = {"Hi": 100, "there": 121, "Mark": 189}
print("The dictionary is:")
print(my_dict)
dict_keys = list(my_dict.keys())
print("The keys in the dictionary are:")
print(dict_keys)
dict_values = list(my_dict.values())
print("The values in the dictionary are:")
print(dict_values)
# Find key for value 100
position = dict_values.index(100)
print("The key for value 100 is:")
print(dict_keys[position])
# Find key for value 189
position = dict_values.index(189)
print("The key for value 189 is:")
print(dict_keys[position])
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 key for value 100 is:
Hi
The key for value 189 is:
Mark
Alternative Approach Using Dictionary Comprehension
A more Pythonic way is to use dictionary comprehension to find keys by values ?
my_dict = {"Hi": 100, "there": 121, "Mark": 189}
# Find key for specific value
target_value = 100
key_for_value = [key for key, value in my_dict.items() if value == target_value]
print(f"Key(s) for value {target_value}: {key_for_value}")
# Find all keys for multiple values
target_values = [100, 189]
keys_for_values = {val: [key for key, value in my_dict.items() if value == val]
for val in target_values}
print("Keys for target values:", keys_for_values)
Key(s) for value 100: ['Hi']
Keys for target values: {100: ['Hi'], 189: ['Mark']}
How It Works
The dictionary keys are accessed using
.keys()and converted to a listThe dictionary values are accessed using
.values()and converted to a listThe
index()method finds the position of the target value in the values listThe same position in the keys list gives us the corresponding key
Dictionary comprehension provides a more direct approach for finding keys by values
Conclusion
Use the index() method with list conversion for simple cases. For more complex scenarios or multiple values, dictionary comprehension offers a cleaner and more Pythonic solution.
