Get Key from Value in Dictionary - Python
Last Updated :
07 Jan, 2025
The goal is to find the keys that correspond to a particular value. Since dictionaries quickly retrieve values based on keys, there isn't a direct way to look up a key from a value.
Using next() with a Generator Expression
This is the most efficient when we only need the first matching key. This method uses a generator expression inside the next() function to efficiently retrieve the first matching key for the given value. The generator stops once it finds the first match, making it fast for one-time lookups.
Example:
Python
d = {'a': 1, 'b': 2, 'c': 2}
tar = 2
# Find all keys for the value 2
keys = [key for key, val in d.items() if val == tar]
print(keys)
Explanation:
- d.items(): Iterates over all key-value pairs in the dictionary.
- Generator Expression: (key for key, val in d.items() if val == tar) yields the first key where the value matches tar.
- next(): Retrieves the first matching key. If no match is found, it returns None.
Let's explore other methods to get key from value in Dictionary:
Using Dictionary Comprehension
Dictionary comprehension provides a concise way to find all keys that correspond to the given value. It processes the entire dictionary and returns a list of all matching keys.
Example:
Python
d = {'a': 1, 'b': 2, 'c': 2}
tar = 2
# Find all keys for the value 2
keys = [key for key, val in d.items() if val == tar]
print(keys)
Explanation:
- [key for key, val in d.items() if val == tar] iterates through the dictionary, collecting all keys where the value matches val.
- keys: Stores the list of matching keys.
Using filter()
filter() function can be used to filter out keys where their value matches the target. The result is an iterable that can be converted to a list.
Example:
Python
d = {'a': 1, 'b': 2, 'c': 2}
val = 2
# Find all keys for the value 2 using filter
keys = list(filter(lambda key: d[key] == val, d))
print(keys)
Explanation:
- filter() takes a lambda function and an iterable. Lambda checks if the value associated with each key matches value_to_find.
- list() converts the filtered iterable into a list of keys.
Using defaultdict (for multiple keys with the same value)
This method uses defaultdict to group keys by their corresponding values. It is useful when we need to handle cases where multiple keys share the same value.
Python
from collections import defaultdict
d = {'a': 1, 'b': 2, 'c': 2}
tar = 2
# Using defaultdict to group keys by values
res = defaultdict(list)
for key, val in d.items():
res[val].append(key)
# Print all keys that correspond to the value 2
print(res[tar])
Explanation:
- defaultdict(list): Creates a dictionary where each value is a list that will hold all keys corresponding to that value.
- for key, val in d.items():: Iterates through the dictionary.
- res[val].append(key): Appends each key to the list of the value in the defaultdict.
Inverting Dictionary (for Reverse Lookup)
Inverting dictionary swaps keys and values so that we can perform reverse lookups. However, if multiple keys have the same value, only the last key will be retained.
Example:
Python
d1 = {'a': 1, 'b': 2, 'c': 3}
val = 2
# Invert the dictionary
d2 = {v: k for k, v in d1.items()}
# Print the key corresponding to the value 2
print(d2.get(val))
Explanation:
- {v: k for k, v in d1.items()}: Creates a new dictionary where the keys and values are swapped. This allows for quick reverse lookups.
- d2.get(val): Looks up the original key for the given value. Since only one key can correspond to a value, this method works best when values are unique.
Using a for loop
This method iterates over the dictionary using a for loop, checking each key-value pair. When a match is found, it immediately returns the key and exits the loop.
Example:
Python
d = {'a': 1, 'b': 2, 'c': 3}
tar = 2
# Find the first key for the value 2
for key, val in d.items():
if val == tar:
print(key)
break
Explanation:
- d.items(): Iterates through each key-value pair.
- if val == tar:: Checks if the value matches the target.
- print(key): Prints the first matching key and exits the loop with break to avoid further unnecessary checks.
Similar Reads
Python dictionary values() values() method in Python is used to obtain a view object that contains all the values in a dictionary. This view object is dynamic, meaning it updates automatically if the dictionary is modified. If we use the type() method on the return value, we get "dict_values object". It must be cast to obtain
2 min read
Return Dictionary from a Function in Python Returning a dictionary from a function allows us to bundle multiple related data elements and pass them back easily. In this article, we will explore different ways to return dictionaries from functions in Python.The simplest approach to returning a dictionary from a function is to construct it dire
3 min read
Dictionary with Tuple as Key in Python Dictionaries allow a wide range of key types, including tuples. Tuples, being immutable, are suitable for use as dictionary keys when storing compound data. For example, we may want to map coordinates (x, y) to a specific value or track unique combinations of values. Let's explores multiple ways to
4 min read
Python Dictionary get() Method Python Dictionary get() Method returns the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument).Python Dictionary get() Method Syntax:Syntax : Dict.get(key, Value)Parameters: key: The key name of the item you want to return
3 min read
How to read Dictionary from File in Python? In Python, reading a dictionary from a file involves retrieving stored data and converting it back into a dictionary format. Depending on how the dictionary was savedâwhether as text, JSON, or binary-different methods can be used to read and reconstruct the dictionary for further use in your program
3 min read