VOOZH about

URL: https://www.geeksforgeeks.org/python/python-remove-keys-with-k-value/

⇱ Python - Remove Keys with K value - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Remove Keys with K value

Last Updated : 15 Jul, 2025

We are given a dictionary we need to remove the keys with K value. For example, we are having a dictionary d = {'a': 1, 'b': 2, 'c': 1, 'd': 3} we need to remove the keys which is having K value so that the output should be {'b': 2, 'd': 3} . We can use dictionary comprehension and many other methods to remove keys.

Using Dictionary Comprehension

We can use dictionary comprehension to create a new dictionary excluding the key-value pairs with the specified value.


Output
{'b': 2, 'd': 3}

Explanation:

  • Dictionary Comprehension Iterates through each key-value pair in dictionary d and includes only pairs where the value is not equal to K (which is 1 in this case).
  • Resulting Dictionary new dictionary res contains filtered key-value pairs where the value is not equal to K effectively removing all keys with the value 1

Using dict.items()

Iterate through dictionary and remove keys with the value K by using the del statement.


Output
{'b': 2, 'd': 3}

Explanation:

  • Identify Keys to Remove list comprehension creates a list k containing the keys where value is equal to K (1), which are the keys 'a' and 'c'.
  • Remove Keys from Dictionary for loop iterates through the list k and removes the corresponding key-value pairs from the dictionary d using the del statement.

Using filter() and lambda

We can use the filter() function in combination with a lambda expression to filter out keys with value K.


Output
{'b': 2, 'd': 3}

Explanation:

  • filter() Function filters the items in the dictionary d by applying the lambda function, which checks whether the value is not equal to K (1).
  • dict() Conversion filter() function returns an iterable so dict() is used to convert it back into a dictionary resulting in res containing only key-value pairs where value is not equal to K.

Using collections.defaultdict

This approach can be helpful if you're working with defaultdict and need to maintain some default behavior


Output
{'b': 2, 'd': 3}

Explanation:

  • Create a defaultdict and Filter Keys defaultdict is created with a default value of 0 and some predefined key-value pairs. Then a dictionary comprehension filters out key-value pairs where the value equals K (which is 1).
  • Resulting Dictionary resulting dictionary res contains only the key-value pairs where the value is not equal to K effectively removing all keys with value 1.
Comment