Open In App

Python – Convert Nested Dictionary into Flattened Dictionary

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

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.

Python
a = {
    'a': 1,
    'b': {'x': 2, 'y': {'z': 3}},
    'c': {'m': 4}
}

f = {}
stack = [(a, '')]  # Stack holds tuples of (current_dict, current_key)

while stack:
    c, p = stack.pop()
    
    for k, v in c.items():
        new_key = f"{p}_{k}" if p else k
        
        if isinstance(v, dict):
            stack.append((v, new_key))  # Push the nested dictionary onto the stack
        else:
            f[new_key] = v  # Add to the flattened dictionary

print(f)

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.

Python
from collections import deque

a = {
    'a': 1,
    'b': {'x': 2, 'y': {'z': 3}},
    'c': {'m': 4}
}

f = {}
queue = deque([(a, '')])  # Queue holds tuples of (current_dict, current_key)

while queue:
    c, p = queue.popleft()
    
    for k, v in c.items():
        new_key = f"{p}_{k}" if p else k
        
        if isinstance(v, dict):
            queue.append((v, new_key))  # Add nested dictionaries to the queue
        else:
            f[new_key] = v 

print(f)

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.


Next Article

Similar Reads