How to access nested Python dictionary items via a list of keys?

When working with nested Python dictionaries, you often need to access deeply buried values using a sequence of keys. Python provides several approaches to safely navigate through nested dictionary structures.

Using a For Loop

The most readable approach is to iterate through each key in the path ?

def getFromDict(dataDict, mapList):
    for k in mapList: 
        dataDict = dataDict[k]
    return dataDict

a = {
    'foo': 45,
    'bar': {
        'baz': 100,
        'tru': "Hello"
    }
}

print(getFromDict(a, ["bar", "baz"]))
100

Using reduce() Function

A more functional approach using reduce() from the functools module ?

from functools import reduce
import operator

data = {
    'level1': {
        'level2': {
            'level3': 'target_value'
        }
    }
}

keys = ['level1', 'level2', 'level3']
result = reduce(operator.getitem, keys, data)
print(result)
target_value

Safe Access with Exception Handling

Handle missing keys gracefully by returning a default value ?

def safe_get_nested(data, keys, default=None):
    try:
        for key in keys:
            data = data[key]
        return data
    except (KeyError, TypeError):
        return default

nested_dict = {
    'users': {
        'john': {'age': 30, 'city': 'New York'}
    }
}

# Existing path
print(safe_get_nested(nested_dict, ['users', 'john', 'age']))

# Non-existing path
print(safe_get_nested(nested_dict, ['users', 'jane', 'age'], 'Not Found'))
30
Not Found

Comparison

Method Error Handling Best For
For Loop None (raises KeyError) Simple, guaranteed paths
reduce() None (raises KeyError) Functional programming style
Exception Handling Returns default value Uncertain data structures

Conclusion

Use the for loop approach for simple cases with guaranteed key paths. For production code with uncertain data structures, implement exception handling to avoid KeyError exceptions and return meaningful default values.

Updated on: 2026-03-24T20:33:19+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements