Sobes.tech
Junior — Middle

How can you swap the values of two variables in programming?

sobes.tech AI

Answer from AI

In Python, to safely access a nested dictionary value when the key may not exist, 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.