Open In App

Python - Extract values of Particular Key in Nested Values

Last Updated : 30 Jan, 2025
Comments
Improve
Suggest changes
4 Likes
Like
Report

We are given a nested dictionary we need to extract the values of particular key. For example, we are having a dictionary d = {'a': 1,'b': {'a': 2, 'c': 3},'d': [{'a': 4}, {'a': 5}]} we need to to extract values from it. so that output becomes [1, 5, 4, 2].

Using a Stack

We can manually manage a stack to iterate through the nested dictionary and lists.


Output
[1, 5, 4, 2]

Explanation:

  • Code uses a stack to explore a nested dictionary/list, processing each element without recursion.
  • It collects values of specified key from dictionaries adding nested dictionaries/lists to stack for further exploration.

Using a Queue

Alternatively we can use a queue to explore structure in a breadth-first manner.


Output
[1, 2, 4, 5]

Explanation:

  • Code uses a queue (deque) to traverse a nested dictionary/list structure level by level processing each element iteratively.
  • It collects values of specified key from dictionaries and adds nested dictionaries/lists to queue for further exploration.

Iterate Through Structure

If we know structure is only a few levels deep (e.g., a dictionary containing lists or other dictionaries) we can use direct iteration without recursion or extra data structures.


Output
[1, 2, 4, 5]

Explanation:

  • Iterates through the top-level dictionary checking for the specified key and exploring nested dictionaries or lists.
  • Checks nested dictionaries and lists for key matches appending values to the result list.

Next Article

Similar Reads