Access Nested Dictionary Items in Python

In Python, you can access nested dictionary items using the following methods:

(1) Using square brackets []

You can use square brackets [] to access nested dictionary items by specifying each key level in order.

For example:

data = {
    'user': {
        'name': 'James',
        'age': 37,
        'address': {
            'city': 'Houston',
            'zipcode': 77005
        }
    }
}

name = data["user"]["name"]
city = data["user"]["address"]["city"]

print(name) # James
print(city) # Houston

If a key is missing, it raises a KeyError. You can use try-except block to handle this error.

data = {
    'user': {
        'name': 'James',
        'age': 37,
        'address': {
            'city': 'Houston',
            'zipcode': 77005
        }
    }
}

try:
    name = data["user"]["name"]
    print(name)
    
    city = data["user"]["dog"]["city"]
    print(city)
except KeyError as e:
    print(f"Key not found {e}")

Output:

James
Key not found 'dog'

(2) Using get() method

You can access items in a nested dictionary by chaining the get() method with each key. This approach is safer, as it returns a default value if a key is missing, instead of raising a KeyError.

For example:

data = {
    'user': {
        'name': 'James',
        'age': 37,
        'address': {
            'city': 'Houston',
            'zipcode': 77005
        }
    }
}

name = data.get("user", {}).get("name", {})
city = data.get("user", {}).get("address", {}).get("city", {})

print(name) # James
print(city) # Houston

Use empty dictionary {} as the default value in get() method when you expect that the next step may involve a dictionary. If a key is missing and you return None, any subsequent attempts to call get() on None will lead to AttributeError. This can break your chain of access.

(3) Using functools.reduce()

You can use reduce() function from the functools module to access items from a nested dictionary. This is useful for retrieving deeply nested values.

For example:

from functools import reduce
data = {
    'user': {
        'name': 'James',
        'age': 37,
        'address': {
            'city': 'Houston',
            'zipcode': 77005
        }
    }
}

# Define the keys in order
keys = ['user', 'address', 'city']

# Use reduce to access the nested value
city = reduce(lambda d, key: d.get(key, {}), keys, data)

print(city) # Output: Houston

The lambda function navigates through the dictionary by using each key in keys list, and at each step, it uses the get() method to retrieve the corresponding value from the dictionary. If a key doesn’t exist, it returns an empty dictionary {} instead of raising an error.

Choosing the right method

Use square brackets [] when you are certain that all the keys exist in the dictionary.

Use get() method when you want a safer approach that prevents errors in case a key is missing.

Use functools.reduce()method when dealing with deeply nested dictionaries