Last Updated : 12 Jul, 2025
Sometimes, we need to remove keys whose values contain a specific substring. For example, consider the dictionary d = {'name1': 'hello world', 'name2': 'python code', 'name3': 'world peace'}. If we want to remove keys where the value contains the substring 'world', the resulting dictionary should exclude such entries. Let's explore multiple methods to achieve this.
Using Dictionary ComprehensionUsing dictionary comprehension is the most efficient method for removing keys with substring values.
Python
# Example
d = {'name1': 'hello world', 'name2': 'python code', 'name3': 'world peace'}
substring = 'world'
# Remove keys where values contain the substring
d = {k: v for k, v in d.items() if substring not in v}
print(d)
{'name2': 'python code'}
Explanation:
Let's explores some more ways to remove keys with substring values in Python dictionaries.
Using del() with for LoopThis method uses for loop to delete keys from the dictionary while iterating over its items.
Python
# Example
d = {'name1': 'hello world', 'name2': 'python code', 'name3': 'world peace'}
substring = 'world'
# Collect keys to remove
keys_to_remove = [k for k, v in d.items() if substring in v]
# Remove the keys
for k in keys_to_remove:
del d[k]
print(d)
{'name2': 'python code'}
Explanation:
This method filters out key-value pairs and reconstructs the dictionary.
Python
# Example
d = {'name1': 'hello world', 'name2': 'python code', 'name3': 'world peace'}
substring = 'world'
# Filter out keys with substring values
d = dict(filter(lambda item: substring not in item[1], d.items()))
print(d)
{'name2': 'python code'}
Explanation:
This method creates a temporary dictionary to store key-value pairs without the substring.
Python
# Example
d = {'name1': 'hello world', 'name2': 'python code', 'name3': 'world peace'}
substring = 'world'
# Create a temporary dictionary
temp = {}
for k, v in d.items():
if substring not in v:
temp[k] = v
d = temp
print(d)
{'name2': 'python code'}
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4