Open In App

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

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a dictionary with key-value pairs, remove all the keys with values greater than K, including mixed values.

Input : test_dict = {‘Gfg’ : 3, ‘is’ : 7, ‘best’ : 10, ‘for’ : 6, ‘geeks’ : ‘CS’}, K = 7 
Output : {‘Gfg’ : 3, ‘for’ : 6, ‘geeks’ : ‘CS’} 
Explanation : All values greater than K are removed. Mixed value is retained. 

Input : test_dict = {‘Gfg’ : 3, ‘is’ : 7, ‘best’ : 10, ‘for’ : 6, ‘geeks’ : ‘CS’}, K = 1 
Output : {‘geeks’ : ‘CS’} 
Explanation : Only Mixed value is retained.

Method #1: Using isinstance() + loop 

This is one of the ways in which this task can be performed. In this, we use instance to get integral values and comparisons to get values not greater than K.

Python3




# Python3 code to demonstrate working of
# Remove keys with Values Greater than K ( Including mixed values )
# Using loop + isinstance()
 
# initializing dictionary
test_dict = {'Gfg' : 3, 'is' : 7, 'best' : 10, 'for' : 6, 'geeks' : 'CS'}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
K = 6
 
# using loop to iterate keys of dictionary
res = {}
for key in test_dict:
   
    # testing for data type and then condition, order is imp.
    if not (isinstance(test_dict[key], int) and test_dict[key] > K):
        res[key] = test_dict[key]
         
# printing result
print("The constructed dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 3, 'is': 7, 'best': 10, 'for': 6, 'geeks': 'CS'}
The constructed dictionary : {'Gfg': 3, 'for': 6, 'geeks': 'CS'}

Time complexity: O(n), where n is the number of keys in the dictionary.
Auxiliary space: O(m), where m is the number of keys that satisfy the condition (values greater than K and of type int). 

Method #2 : Using dictionary comprehension + isinstance()

The combination of above functions is used to solve this problem. This performs task similar to above method. The only difference being that it performs in one liner using dictionary comprehension.

Python3




# Python3 code to demonstrate working of
# Remove keys with Values Greater than K ( Including mixed values )
# Using dictionary comprehension + isinstance()
 
# initializing dictionary
test_dict = {'Gfg' : 3, 'is' : 7, 'best' : 10, 'for' : 6, 'geeks' : 'CS'}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
K = 6
 
# using list comprehension to perform in one line
res = {key : val for key, val in test_dict.items() if not (isinstance(val, int) and (val > K))}
         
# printing result
print("The constructed dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 3, 'is': 7, 'best': 10, 'for': 6, 'geeks': 'CS'}
The constructed dictionary : {'Gfg': 3, 'for': 6, 'geeks': 'CS'}

Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary space: O(n).

Method #3: Using dictionary comprehension and filter()

We can also solve this problem using a combination of dictionary comprehension and the built-in function filter().

Step-by-step approach:

  • Initialize the original dictionary test_dict.
  • Print the original dictionary.
  • Initialize the variable K with the value 6.
  • Use the filter() function to remove keys with values greater than K. To do this, we create a lambda function that takes a key-value pair as input and returns True if the value is not an integer or if it is an integer but is less than or equal to K. We then pass this lambda function to filter() along with the items of test_dict using the items() method. Finally, we convert the filtered items back to a dictionary using the dict() constructor and store it in the variable res.
  • Print the constructed dictionary.

Below is the implementation of the above approach:

Python3




# initializing dictionary
test_dict = {'Gfg': 3, 'is': 7, 'best': 10, 'for': 6, 'geeks': 'CS'}
 
# printing original dictionary
print("The original dictionary is: " + str(test_dict))
 
# initializing K
K = 6
 
# using filter() and dictionary comprehension to construct a new dictionary
res = dict(filter(lambda item: not (isinstance(item[1], int) and item[1] > K), test_dict.items()))
 
# printing result
print("The constructed dictionary: " + str(res))


Output

The original dictionary is: {'Gfg': 3, 'is': 7, 'best': 10, 'for': 6, 'geeks': 'CS'}
The constructed dictionary: {'Gfg': 3, 'for': 6, 'geeks': 'CS'}

Time complexity: O(n), where n is the number of key-value pairs in the dictionary. This is because we need to iterate over each key-value pair in the dictionary once.
Auxiliary space: O(m), where m is the number of key-value pairs in the new dictionary. This is because we need to create a new dictionary to store the filtered key-value pairs.



Similar Reads

Python - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 min read
Python - Test if Values Sum is Greater than Keys Sum in dictionary
Given a Dictionary, check if the summation of values is greater than the keys sum. Input : test_dict = {5:3, 1:3, 10:4, 7:3, 8:1, 9:5} Output : False Explanation : Values sum = 19 < 40, which is key sum, i.e false.Input : test_dict = {5:3, 1:4} Output : True Explanation : Values sum = 7 > 6, which is key sum, i.e true. Method #1: Using loop I
8 min read
Python - Filter and Double keys greater than K
Sometimes, while working with Python dictionaries, we can have the task of extracting certain keys after manipulation and filtration, both at once. This problem can be generalized for other values and operations as well. This has applications in many domains such as day-day programming and web development. Let's discuss certain ways in which this t
7 min read
Python - Maximum column values in mixed length 2D List
The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the maximizations of its columns, the uneven length of rows may lead to some elements in that elements to be absent and if not handled correctly, may throw an exception. Let’s discuss certain ways in which this pr
6 min read
Python - Find all pairs of consecutive odd positive integer smaller than a with sum greater than b
Given two positive integers a and b, the task is to write a program in python to find all pairs of consecutive odd numbers which are smaller than the first number a and their sum should be greater than the second number b. Examples: Input: a = 60 b = 100 Output: Pairs of consecutive number are: 51 , 53 53 , 55 55 , 57 57 , 59 Input: a = 20 b = 200
3 min read
Python - Remove keys with substring values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove keys whose values have substring as argument we pass. This problem can occur in cases of web development and day-day programming. Lets discuss certain ways in which this task can be performed. Input : test_dict = {1 : 'Gfg is best for geeks'} sub_lis
6 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python - Remove Tuples with difference greater than K
Given Dual Tuples List, remove pairs with differences greater than K. Input : test_list = [(4, 8), (1, 7), (9, 12), (3, 12), (2, 10)], K = 6 Output : [(4, 8), (9, 12), (1, 7)] Explanation : 4 (8 - 4), 3 (12 - 9) and 6 are all not greater than 6, hence retained. Input : test_list = [(4, 8), (1, 7), (9, 12), (3, 12), (2, 10)], K = 3 Output : [(9, 12)
5 min read
Python - Remove characters greater than K
Given the Strings list, remove all the characters from each string that have characters greater than K. Input : test_list = ["geeksforgeeks", "is", "best", "for", "geeks"], K = 13 Output : ['geekfgeek', 'i', 'be', 'f', 'geek'] Explanation : ASCII Characters above m are removed. Input : test_list = ["geeksforgeeks", "is", "best", "for", "geeks"], K
7 min read
Python | String Split including spaces
The problems and at the same time applications of list splitting are quite common while working with python strings. The spaces usually tend to ignore in the use cases. But sometimes, we might not need to omit the spaces but include them in our programming output. Let's discuss certain ways in which this problem can be solved. Method #1: Using spli
4 min read
Practice Tags :
three90RightbarBannerImg