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_list = [‘love’, ‘good’] ( Strings to check in values )
Output : {1: ‘Gfg is best for geeks’}Input :
test_dict = {1 : ‘Gfg is love’, 2: ‘Gfg is good’}
sub_list = [‘love’, ‘good’] ( Strings to check in values )
Output : {}
Method #1 : Using any() + loop
The combination of above functionalities can be used to solve this problem. In this, we extract all the items from dictionary which do not have desired values, the filteration is performed using any() and generator expression.
# Python3 code to demonstrate working of # Remove keys with substring values# Using any() + generator expression # initializing dictionarytest_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # initializing substringssub_list = ['love', 'good'] # Remove keys with substring values# Using any() + generator expressionres = dict()for key, val in test_dict.items(): if not any(ele in val for ele in sub_list): res[key] = val # printing result print("Filtered Dictionary : " + str(res)) |
The original dictionary : {1: ‘Gfg is best for geeks’, 2: ‘Gfg is good’, 3: ‘I love Gfg’}
Filtered Dictionary : {1: ‘Gfg is best for geeks’}
Method #2 : Using dictionary comprehension + any()
The combination of above methods provide the shorthand to execute this task. In this, we perform this task in similar way as above method, but in one liner format using comprehension.
# Python3 code to demonstrate working of # Remove keys with substring values# Using dictionary comprehension + any() # initializing dictionarytest_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # initializing substringssub_list = ['love', 'good'] # Remove keys with substring values# Using dictionary comprehension + any()res = {key : val for key, val in test_dict.items() if not any(ele in val for ele in sub_list)} # printing result print("Filtered Dictionary : " + str(res)) |
The original dictionary : {1: 'Gfg is best for geeks', 2: 'Gfg is good', 3: 'I love Gfg'}
Filtered Dictionary : {1: 'Gfg is best for geeks'}
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


