Open In App

Python - Remove keys with substring values

Last Updated : 27 Jan, 2025
Comments
Improve
Suggest changes
1 Like
Like
Report

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 Comprehension

Using dictionary comprehension is the most efficient method for removing keys with substring values.


Output
{'name2': 'python code'}

Explanation:

  • d.items() generates key-value pairs.
  • The condition substring not in v filters out keys with values containing the substring.
  • A new dictionary is created with the remaining pairs.

Let's explores some more ways to remove keys with substring values in Python dictionaries.

Using del() with for Loop

This method uses for loop to delete keys from the dictionary while iterating over its items.


Output
{'name2': 'python code'}

Explanation:

  • A list comprehension collects keys where the values contain the substring.
  • A loop iterates over these keys, removing them using the del() statement.

Using filter()

This method filters out key-value pairs and reconstructs the dictionary.


Output
{'name2': 'python code'}

Explanation:

  • filter() iterates through the dictionary items.
  • A lambda function ensures only pairs without the substring are retained.
  • The dict() function converts the filtered pairs back to a dictionary.

Using a Temporary Dictionary

This method creates a temporary dictionary to store key-value pairs without the substring.


Output
{'name2': 'python code'}

Explanation:

  • A temporary dictionary temp is initialized.
  • A loop adds key-value pairs without the substring to temp.
  • The original dictionary is replaced with temp

Next Article
Practice Tags :

Similar Reads