VOOZH about

URL: https://www.geeksforgeeks.org/python/python-flatten-and-remove-keys-from-dictionary/

⇱ Flatten and Remove Keys from Dictionary - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Flatten and Remove Keys from Dictionary

Last Updated : 15 Jul, 2025

We are given a dictionary we need to flatten and remove keys from it. For example, we are given a dictionary d = {'a': {'b': 1, 'c': {'d': 2}}, 'e': 3} we need to flatten and remove the keys so that the output should be {'e': 3, 'a.b': 1, 'a.c.d': 2}. We can use itertools and various other approaches.

Using Loops for Flattening

Nested dictionaries are processed iteratively using a stack. Each key is combined with its parent key to form a flattened key. Non-dictionary values are directly added to result while nested dictionaries are pushed back onto stack for further processing.


Output
{'e': 3, 'a.b': 1, 'a.c.d': 2}

Explanation:

  • Stack s is used to iteratively process nested dictionaries constructing hierarchical keys (new_key) by appending the current key to parent_key with a dot separator.
  • Nested dictionaries are added back to the stack while non-dictionary values are stored in flattened dictionary f with their constructed keys.

Using a Queue

We can use a queue for breadth-first traversal instead of depth-first traversal.


Output
{'e': 3, 'a.b': 1, 'a.c.d': 2}

Explanation:

  • Queue (q) processes dictionaries level by level constructing new keys by combining the parent key (p) with current key.
  • Nested dictionaries are added back to the queue while non-dictionary values are added to flattened dictionary (f) with their full keys.

Flattening Using Itertools

Itertools can be used for flattening if keys and values are extracted iteratively.


Output
{'e': 3, 'a.b': 1, 'a.c.d': 2}

Explanation:

  • Stack processes the dictionary in depth-first order constructing new keys by combining the parent key with current key.
  • Nested dictionaries are pushed back to the stack, and non-dictionary values are added to the flattened result.
Comment