Safe method to get value of nested 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.
Introduction
Reading nested dictionaries safely in Python is less about a single trick and more about choosing the right failure mode. Optional fields should return a sensible default, while required fields should fail loudly with a message that explains what is missing.
Use Chained get for Short Optional Paths
If the structure is a dictionary of dictionaries and the path is short, chained get calls are usually the most readable option. Each step makes the default explicit and avoids a KeyError.
This pattern works well for optional data because every missing key cleanly falls back to the next default. It also makes the return type obvious. In the example above, the code always returns a string, not sometimes a string and sometimes None.
The main limitation is that it becomes noisy when the path is long. Once you reach four or five levels, a helper becomes easier to read.
Write a deep_get Helper for Repeated Access
When the same style of lookup appears throughout a codebase, a helper keeps the rules consistent. A good version should stop as soon as the current value is no longer a dictionary.
This approach is especially useful when the path comes from configuration or when you need the same access policy in many modules. The helper also documents the intended behavior better than repeating a long series of get calls everywhere.
Distinguish Optional Data from Required Data
One of the most common mistakes is treating required fields as optional by giving them a default. That hides bad input and pushes the error deeper into the program.
For required data, retrieve it and validate it immediately:
That code is stricter, but it fails at the correct place. Instead of letting a later database call or template render fail with a vague error, the parser explains exactly which field is broken.
Guard Against Wrong Intermediate Types
Missing keys are only one failure mode. Real payloads can also contain the wrong shape. For example, "user" might be None or a list due to a bad upstream response.
Type guards like this are useful when the source is untrusted. They prevent crashes caused by shape mismatches, not just absent keys.
Avoid Broad try/except for Lookup Logic
It is tempting to write one try/except block around a direct lookup chain:
Even this narrower version is less flexible than explicit access rules, because it only handles missing keys. If the intermediate value is the wrong type, the code raises a different exception. A broad except Exception would catch too much and could hide real bugs.
In practice, direct indexing is best reserved for validated data structures where missing keys truly indicate a programming error.
Common Pitfalls
- Using direct indexing on API payloads that are not guaranteed to have every key.
- Returning inconsistent fallback values, such as
Nonein one branch and a string in another. - Treating required fields as optional by silently inserting defaults.
- Forgetting that an intermediate value can be the wrong type, not just absent.
- Catching broad exceptions and accidentally masking unrelated bugs.
Summary
- Use chained
getfor short optional paths. - Use a
deep_gethelper when the lookup pattern repeats or the path is dynamic. - Validate required fields explicitly instead of defaulting them.
- Add type guards when upstream data may have the wrong shape.
- Prefer explicit access rules over broad
try/exceptblocks.
Related reading
- Sample Directed Graph and Topological Sort Code
- Save PHP array to MySQL?
- Save Tensorflow graph for viewing in Tensorboard without summary operations
- Saving a Numpy array as an image
- Safest way to convert float to integer in python?
- sample weights in scikit-learn broken in cross validation
- Saving and reading variable size list from TFRecord
- Scala Wait while List is beeing filled

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.