VOOZH about

URL: https://www.geeksforgeeks.org/python/python-convert-nested-dictionary-into-flattened-dictionary/

⇱ Python - Convert Nested Dictionary into Flattened Dictionary - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Convert Nested Dictionary into Flattened Dictionary

Last Updated : 11 Jul, 2025

We are given a nested dictionary we need to flatten the dictionary into single dictionary. For example, we are given a nested dictionary a = {'a': 1, 'b': {'x': 2, 'y': {'z': 3}}, 'c': {'m': 4} } we need to flatten the dictionary so that output becomes {'a': 1, 'c_m': 4, 'b_x': 2, 'b_y_z': 3}. We can use stack and queues for flattening it.

Using a Stack

Using a stack, we push tuples of the current dictionary and its parent key, then pop them to flatten nested dictionaries by concatenating keys. If a value is a dictionary then it's pushed back onto the stack for further processing.


Output
{'a': 1, 'c_m': 4, 'b_x': 2, 'b_y_z': 3}

Explanation:

  • Stack stores tuples of the current dictionary and its parent key; we process each dictionary, concatenating keys and adding key-value pairs to the flattened dictionary.
  • If a value is a nested dictionary then it is pushed back onto the stack for further flattening, otherwise the key-value pair is added to the result.

Using a Queue

Using a queue, we enqueue tuples of the current dictionary and its parent key, then dequeue them to process the dictionary and flatten it. If a value is a nested dictionary, it's enqueued for further processing.


Output
{'a': 1, 'b_x': 2, 'c_m': 4, 'b_y_z': 3}

Explanation:

  • Queue stores tuples of the current dictionary and its parent key; we dequeue them to process and flatten the dictionary by concatenating keys.
  • If a value is a nested dictionary then it is enqueued for further processing otherwise the key-value pair is added to the flattened result.
Comment