VOOZH about

URL: https://www.geeksforgeeks.org/python/python-get-particular-nested-level-items-from-dictionary/

⇱ Get particular Nested level Items from Dictionary - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Get particular Nested level Items from Dictionary - Python

Last Updated : 15 Jul, 2025

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.


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.


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.
Comment