VOOZH about

URL: https://www.geeksforgeeks.org/python/python-remove-k-value-items-from-dictionary-nesting/

⇱ Remove K Value Items from Dictionary Nesting - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove K Value Items from Dictionary Nesting - Python

Last Updated : 15 Jul, 2025

We are given a dictionary we need to remove K value items from dictionary. For example we are having a dictionary d = {'a': {'b': 'remove', 'c': 'keep'}, 'd': {'e': 'remove', 'f': 'keep'}} we need to remove the K value suppose in this case K is 'remove' so that output should be {'a': {'c': 'keep'}, 'd': {'f': 'keep'}}.

Using Iterative Traversal

Iterative traversal uses a stack or queue to navigate through a nested dictionary layer by layer checking each key-value pair. If a value matches K it is removed and if a value is a nested dictionary.


Output
{'a': {'c': 'keep'}, 'd': {'f': 'keep'}}

Explanation:

  • Given code uses a stack (s) to iteratively traverse through nested dictionaries processing one dictionary at a time. It collects keys with values equal to K and removes them from current dictionary.
  • If value is a nested dictionary it is added to stack for further processing ensuring all levels of dictionary are checked and updated as needed.

Using While Loop

In this method we are using a while loop to traverse through the dictionary and its nested dictionaries. It identifies and removes key-value pairs where value matches K then adds any nested dictionaries to loop for further inspection ensuring all levels are handled.


Output
{'a': {'c': 'keep'}, 'd': {'f': 'keep'}}

Explanation:

  • While loop traverses dictionary and its nested dictionaries checking each key-value pair to see if the value matches K. If a match is found corresponding key-value pair is deleted.
  • If the value is a dictionary it is added to "a" list ensuring that all nested dictionaries are processed for matching key-value pairs.

Using a Queue

In this method we use a queue for traversal and add the dictionary to the queue to process each key-value pair. If a nested dictionary is found then it is enqueued for further checking and matching key-value pairs are removed during iteration.


Output
{'a': {'c': 'keep'}, 'd': {'f': 'keep'}}

Explanation:

  • Code uses a queue (deque) to traverse through a nested dictionary iterating over each key and removes key-value pairs where value matches K.
  • It continues traversing any nested dictionaries by adding them to queue ensuring all nested levels are processed until all matching key-value pairs are removed.
Comment