Why dict.get(key) instead of dict[key]?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
In Python, dictionaries are a type of data structure that store data in key-value pairs. When it comes to retrieving values from a dictionary, Python provides primarily two methods: using the square brackets dict[key] and using the dict.get(key) method. Each method has its particular use case, benefits, and limitations.
Understanding dict[key]
When you use dict[key] to access a value in a dictionary, you directly retrieve the value associated with the provided key. However, if the key does not exist in the dictionary, Python will raise a KeyError.
Example:
This method is straightforward and fast but lacks flexibility when the key might not always be present in the dictionary.
Understanding dict.get(key)
The dict.get(key) method offers a more flexible approach. It returns the value for the key if it exists in the dictionary. If the key does not exist, it returns None instead of raising a KeyError. Moreover, dict.get(key, default) allows you to specify a default value that should be returned if the key is missing.
Example:
This method is particularly useful when it is acceptable or likely for the key not to be present, and you want to avoid handling exceptions or you need a default value.
When to Use Each Method
- Performance Critical Code: If you are certain a key exists and performance is a priority,
dict[key]is faster because it doesn't involve the overhead of a function call. - Robustness Against Missing Keys: If there’s a chance that the key might not be present and the program should continue running, use
dict.get(key). - Default Values: When you need to provide a fallback value for missing keys,
dict.get(key, default)is a clean and efficient way.
Summary Table
| Feature | dict[key] | dict.get(key) |
| Key Exists | Returns value | Returns value |
| Key Missing | Raises KeyError | Returns None or specified default value |
| Performance | Slightly faster, no function call overhead | Slightly slower due to function call |
| Use Case | When key is guaranteed to exist | Flexible, especially when key might not exist |
Advanced Usage and Considerations
Error Handling
When using dict[key], it’s often wise to handle potential KeyErrors to prevent your program from crashing unexpectedly:
This approach can get verbose, which is why dict.get(key, default) can be preferable in many scenarios.
Immutable Default Values
When using dict.get(key, default), ensure that the default value is immutable. Using mutable objects as defaults (like lists or dictionaries) can lead to unexpected behavior if the default object is modified.
Dict Subclasses and Overrides
Remember that the behavior of dict[key] and dict.get(key) can be overridden in subclasses of dict. This might change how these methods behave, but generally, the principles discussed still apply.
Conclusion
Choosing between dict[key] and dict.get(key) often depends on the specific requirements and constraints of your application. Both are useful tools in a Python programmer's toolkit, and understanding their nuances enables writing cleaner, more efficient, and error-resistant code.
Related reading
- Why dict.getkey instead of dictkey?
- Why do all-pair shortest path algorithms work with negative weights?
- Why do C multidimensional arrays not implement IEnumerableT?
- Why do I get an UnsupportedOperationException when trying to remove an element from a List?
- Why do I get AttributeError module 'tensorflow' has no attribute 'placeholder'?
- Why do I get AttributeError 'NoneType' object has no attribute 'something'?
- Why do python lists have pop but not push
- Why do we need routing key in RabbitMQ?

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 courseTrack 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.