Sobes.tech
Junior — Middle

How to safely get a value by key from a nested dictionary if you're not sure whether the key exists?

sobes.tech AI

Answer from AI

To safely retrieve a value by key from a nested dictionary (dictionary within a dictionary) in Python, when it’s not known whether the key exists, you can use the dict.get() method or handle exceptions.

Example with get():

nested_dict = {'a': {'b': 42}}

# Safe access
value = nested_dict.get('a', {}).get('b')
print(value)  # Will print 42

# If 'a' or 'b' does not exist, returns None
value = nested_dict.get('x', {}).get('y')
print(value)  # None

This approach prevents KeyError and returns None or a default value if the key is missing.