Open In App

Remove K Value Items from Dictionary Nesting – Python

Last Updated : 01 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Python
d = {'a': {'b': 'remove', 'c': 'keep'}, 'd': {'e': 'remove', 'f': 'keep'}}
K = 'remove'

# Stack to hold nested dictionaries
s = [d]

while s:
    c = s.pop()
    
    # Collect keys to delete
    key_del = [k for k, v in c.items() if v == K]
    
    # Delete the keys with value K
    for k in key_del:
        del c[k]
    
    # Add nested dictionaries to the stack for further processing
    for v in c.values():
        if isinstance(v, dict):
            s.append(v)

print(d)

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.

Python
d = {'a': {'b': 'remove', 'c': 'keep'}, 'd': {'e': 'remove', 'f': 'keep'}}
K = "remove"

a = [d]

while a:
    c = a.pop()
    
    for key in list(c.keys()):
        
        # If the value matches 'K', remove the key-value pair
        if c[key] == K:
          	# Remove matching key-value pairs
            del c[key]  
        
        # If value is a nested dictionary add it to the list
        elif isinstance(c[key], dict):
            a.append(c[key])  

print(d)

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.

Python
from collections import deque

d = {'a': {'b': 'remove', 'c': 'keep'}, 'd': {'e': 'remove', 'f': 'keep'}}
K = 'remove'

q = deque([d])  
while q:
    
    # Dequeue the first element
    c = q.popleft()  
    
    for key in list(c.keys()):  
        
         # Remove matching key-value
        if c[key] == K: del c[key] 
        
        # Add nested dicts to queue
        elif isinstance(c[key], dict): q.append(c[key])  

print(d)

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.


Next Article
Practice Tags :

Similar Reads