Open In App

Get Key from Value in Dictionary - Python

Last Updated : 07 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)  

Output
['b', 'c']

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)  

Output
['b', 'c']

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) 

Output
['b', 'c']

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])  

Output
['b', 'c']

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

Output
b

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.

Next Article

Similar Reads