VOOZH about

URL: https://www.geeksforgeeks.org/python/python-remove-keys-with-values-greater-than-k-including-mixed-values/

⇱ Python - Remove keys with Values Greater than K ( Including mixed values ) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Remove keys with Values Greater than K ( Including mixed values )

Last Updated : 15 Jul, 2025

We are given a dictionary we need to remove the keys with values greater than K. For example, we are given a dictionary d = {'a': 1, 'b': 5, 'c': 'hello', 'd': [1, 2, 3]} we need to remove the keys with value greater than K so that output should be {'a': 1, 'c': 'hello', 'd': [1, 2, 3]}. We can use approach like dictionary comprehension, del method and multiple approaches for this.

Using Dictionary Comprehension

Dictionary comprehension allows us to filter key-value pairs based on a condition creating a new dictionary with only desired items.


Output
{'a': 1, 'c': 'hello', 'd': [1, 2, 3]}

Explanation:

  • Dictionary comprehension iterates through each key-value pair in d keeping only those where the value is less than or equal to 3 (for numeric values), or the value is not numeric (like strings or lists).
  • Modified dictionary {'a': 1, 'c': 'hello', 'd': [1, 2, 3]} is printed, excluding the key 'b' since its value (5) is greater than 3

Using del keyword

del keyword is used to remove a specific key-value pair from a dictionary by specifying the key. If the key exists it is deleted otherwise a KeyError is raised.


Output
{'a': 1, 'c': 'hello', 'd': [1, 2, 3]}

Explanation:

  • Code iterates over the keys of the dictionary d, checking if the value associated with each key is a numeric type (int or float) and greater than 3, and if so deletes the key-value pair.
  • Modified dictionary {'a': 1, 'c': 'hello', 'd': [1, 2, 3]} is printed, which excludes the key 'b' as its value (5) is greater than 3.

Using pop()

pop() method removes a key-value pair from a dictionary by specifying key and optionally returns the value. It can be used in a loop to remove keys with specific conditions such as values greater than a given threshold.


Output
{'a': 1, 'c': 'hello', 'd': [1, 2, 3]}

Explanation:

  • Code iterates over keys of the dictionary d and checks if each value is numeric (int or float) and greater than the threshold K = 3. If so, it removes the key-value pair using the pop() method.
  • Modified dictionary {'a': 1, 'c': 'hello', 'd': [1, 2, 3]} is printed, where the key 'b' is excluded because its value (5) exceeds the threshold.
Comment