Programming
Python
Dictionaries
Key-Value Pairs
Coding Techniques

Get key by value in dictionary

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Dictionaries in Python are a fundamental data structure that store data in key-value pairs, enabling quick access to values by their keys. However, there are situations where you might need to retrieve a key using a value, a task that is not as straightforward as the inverse operation. In this article, we will explore how to get a key by value in a Python dictionary and discuss several methods and considerations to handle this operation efficiently.

Understanding the Basics of Python Dictionaries

A dictionary in Python is defined using curly braces {}, with key-value pairs separated by commas. Each key is linked to its corresponding value by a colon :. Keys in dictionaries are unique and are typically strings or numbers, while values can be of any data type and can repeat.

Here's a simple dictionary for demonstration:

python
1person_info = {
2    "name": "Alice",
3    "age": 30,
4    "city": "New York"
5}

Retrieving Key by Value

By default, dictionaries are designed to retrieve value by key, not the other way around. Therefore, if you need to find a key based on a value, you will have to iterate over the dictionary. Here is the basic method to do that:

python
1def get_key_by_value(dict, val):
2    for key, value in dict.items():
3        if value == val:
4            return key
5    return None
6
7# Example Usage
8key = get_key_by_value(person_info, "New York")
9print(key)  # Output: city

This function get_key_by_value takes a dictionary and a value as arguments, iterates through dictionary items, and returns the key when the matching value is found.

Handling Multiple Keys With the Same Value

A value may appear in multiple key-value pairs. If you need to retrieve all keys for a particular value, you can modify the above function to return a list of keys.

python
1def get_all_keys_by_value(dict, val):
2    keys = []
3    for key, value in dict.items():
4        if value == val:
5            keys.append(key)
6    return keys
7
8# Example Usage
9person_info.update({"office_city": "New York", "favourite_city": "New York"})
10keys = get_all_keys_by_value(person_info, "New York")
11print(keys)  # Output: ['city', 'office_city', 'favourite_city']

Performance Considerations

Finding a key by value involves a linear search, which has a time complexity of O(n)O(n), where nn is the number of elements in the dictionary. This is because this operation scans each element until a match is found or all elements have been checked.

Summary Table

MethodUse-caseComplexityReturn TypeConsideration
get_key_by_value()Single key retrievalO(n)O(n)Single key or NoneOnly one key will be returned, even if multiple keys have the same value
get_all_keys_by_value()Multiple keys retrievalO(n)O(n)List of keysUseful when values are not unique and multiple keys need retrieval

Advanced Usage and Tips

  • Looking for Similar Values: For non-exact matches or complex data structures, additional logic might be necessary, like substring matches or threshold-based matches.
  • Using Inverted Dictionaries: If value-to-key retrieval is common in your application, consider maintaining an inverted dictionary where values are keys. This requires extra space but lookup becomes O(1)O(1).
  • Deep Dictionaries: For nested dictionaries, recursive techniques or specialized functions like deep_get() might be used to access keys deeply nested within the dictionary structure.

Conclusion

Retrieving keys by value in a dictionary requires iterating over the dictionary, making it less efficient than key-to-value retrieval. Always consider the characteristics of your data and use cases when choosing how to implement this functionality, and weigh the trade-offs between time complexity and space complexity.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.