Python - Remove K valued key from Nested Dictionary
Last Updated :
01 Feb, 2025
We are given a nested dictionary we need to remove K valued key. For example, we are given a nested dictionary d = { "a": 1, "b": {"c": 2,"d": {"e": 3,"f": 1},"g": 1},"h": [1, {"i": 1, "j": 4}]} we need to remove K valued key ( in our case we took k value as 1 ) from it so that the output should be {'b': {'c': 2, 'd': {'e': 3}}, 'h': [1, {'j': 4}]}. We can use multiple approaches like iterative, list comprehension and various other ways.
Using Iterative Approach
We use a stack to manually handle recursion while traversing the dictionary and removing the k valued key.
Python
d = {"a": 1, "b": {"c": 2, "d": 3}, "h": [1, {"i": 1, "j": 4}]}
a = 1
s = [d]
while s:
c = s.pop()
# Iterate over a copy of the keys
for key in list(c.keys()):
if c[key] == a:
del c[key] # Remove the key if its value matches 'a'
elif isinstance(c[key], dict):
s.append(c[key])
elif isinstance(c[key], list): # If the value is a list
for item in c[key]:
if isinstance(item, dict): # If the item in the list is a dictionary
s.append(item)
print(d)
Output{'b': {'c': 2, 'd': 3}, 'h': [1, {'j': 4}]}
Explanation:
- Traverse the nested dictionary using a stack and process one dictionary at a time.
- Remove keys with the value 1 and add nested dictionaries to the stack.
- Continue until the stack is empty, hence the final dictionary excludes all keys with value 1.
Using Nested Loops and List Comprehensions
This method uses list comprehensions to process dictionaries and lists.
Python
d = {"a": 1, "b": {"c": 2, "d": {"e": 3, "f": 1}, "g": 1}, "h": [1, {"i": 1, "j": 4}]}
a = 1
s = [d]
while s:
c = s.pop()
# Process each key in the dictionary
for key in list(c.keys()):
if c[key] == a:
del c[key] # Delete the key with value 'a'
elif isinstance(c[key], dict): # If the value is a nested dictionary
s.append(c[key])
elif isinstance(c[key], list): # If the value is a list
c[key] = [
item for item in c[key]
if not (isinstance(item, dict) and a in item.values())
]
# Add nested dictionaries
s.extend(item for item in c[key] if isinstance(item, dict))
print(d)
Output{'b': {'c': 2, 'd': {'e': 3}}, 'h': [1]}
Explanation:
- Traverse nested dictionary with a stack, removing keys with value 1 and processing nested dictionaries and lists.
- Continue until stack is empty final dictionary excludes all instances of the value 1
Using del
We can directly use del to delete keys as you iterate through the dictionary.
Python
d = {"a": 1, "b": {"c": 2, "d": {"e": 3, "f": 1}, "g": 1}, "h": [1, {"i": 1, "j": 4}]}
a = 1
s = [d]
while s:
c = s.pop()
k = [key for key, val in c.items() if val == a] # Identify keys with value 'a'
for key in k:
del c[key]
for key, val in c.items(): # Check for nested dictionaries or lists
if isinstance(val, dict):
s.append(val) # Add nested dictionaries to the stack
elif isinstance(val, list):
for item in val:
if isinstance(item, dict):
s.append(item) # Add dictionaries
print(d)
Output{'b': {'c': 2, 'd': {'e': 3}}, 'h': [1, {'j': 4}]}
Explanation:
- Traverse the nested dictionary with a stack, removing keys with value 1 and adding nested dictionaries and lists to the stack.
- Continue until the stack is empty; the final dictionary excludes all keys with the value 1.
Similar Reads
Remove K Value Items from Dictionary Nesting - Python 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'},
3 min read
Python Remove Item from Dictionary by Value We are given a dictionary and our task is to remove key-value pairs where the value matches a specified target. This can be done using various approaches, such as dictionary comprehension or iterating through the dictionary. For example: d = {"a": 10, "b": 20, "c": 10, "d": 30} and we have to remove
3 min read
Remove Spaces from Dictionary Keys - Python Sometimes, the keys in a dictionary may contain spaces, which can create issues while accessing or processing the data. For example, consider the dictionary d = {'first name': 'Nikki', 'last name': 'Smith'}. We may want to remove spaces from the keys to standardize the dictionary, resulting in {'fir
3 min read
Remove Kth Key from Dictionary - Python We are given a dictionary we need to remove Kth key from the dictionary. For example, we are given a dictionary d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'} we need to remove the key2 so that the output should be {'key1': 'value1', 'key3': 'value3', 'key4': 'value4'}.
3 min read
Python Get All Values from Nested Dictionary In this article, we will learn how we can Get all Values from Nested Dictionary in Python Programming. A nested Dictionary in Python is a dictionary that contains another dictionary as its values. Using this, we can create a nested structure where each of the key-value pairs is in the outer dictiona
5 min read