Our task is to extract all items at a particular depth level from a given nested dictionary,. This means retrieving only the key-value pairs that exist at a specific depth within the dictionary. For example: d = {'a': {'b': {'c': 5, 'd': 6}, 'e': 7}, 'f': 8} and if we want all key-value pairs at level 2 then the output should be: {'b': {'c': 5, 'd': 6}, 'e': 7}.
Using reduce() from functool
In this method we use reduce() to traverse the dictionary level by level extracting key-value pairs at the required depth.
from functools import reduce
d = {'a': {'b': {'c': 5, 'd': 6}, 'e': 7}, 'f': 8}
lvl = 2
res = reduce(lambda d, _: {k: v for v in d.values() if isinstance(v, dict) for k, v in v.items()}, range(lvl - 1), d)
print(res)
Output
{'b': {'c': 5, 'd': 6}, 'e': 7}
Explanation:
- reduce() iterates lvl - 1 times and this ensures we extract key-value pairs at the correct level without going too deep.
- d.values() selects only nested dictionaries: we ignore non-dictionary values and focus on deeper levels.
- Dictionary comprehension {k: v for k, v in v.items()} this flattens the nested dictionaries while preserving structure.
Using update() with Iteration
We use a stack to traverse the dictionary iteratively and extract key-value pairs at the required depth.
data = {'a': {'b': {'c': 5, 'd': 6}, 'e': 7}, 'f': 8}
lvl, res = 2, {}
stk = [(data, 0)]
while stk:
d, depth = stk.pop()
if depth == lvl - 1:
res.update({k: v for k, v in d.items() if isinstance(v, dict)})
for v in d.values():
if isinstance(v, dict):
stk.append((v, depth + 1))
print(res)
Output
{'b': {'c': 5, 'd': 6}}
Explanation:
- stk stores dictionaries along with their depth.
- If depth == lvl - 1 then we use update() to add key-value pairs where values are dictionaries.
- We traverse values adding nested dictionaries to stk with increased depth.