Python – 删除带有子字符串值的键
有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要删除其值具有子字符串作为我们传递的参数的键。在 Web 开发和日常编程的情况下可能会出现此问题。让我们讨论可以执行此任务的某些方式。
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 : {}
方法 #1:使用 any() + 循环
上述功能的组合可以用来解决这个问题。在此,我们从字典中提取所有没有所需值的项目,使用 any() 和生成器表达式执行过滤。
Python3
# Python3 code to demonstrate working of
# Remove keys with substring values
# Using any() + generator expression
# initializing dictionary
test_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing substrings
sub_list = ['love', 'good']
# Remove keys with substring values
# Using any() + generator expression
res = 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))
Python3
# Python3 code to demonstrate working of
# Remove keys with substring values
# Using dictionary comprehension + any()
# initializing dictionary
test_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing substrings
sub_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))
输出 :
原词典:{1: 'Gfg is best for geeks', 2: 'Gfg is good', 3: 'I love Gfg'}
过滤字典:{1: 'Gfg 最适合极客'}
方法 #2:使用字典理解 + any()
上述方法的组合提供了执行此任务的简写。在此,我们以与上述方法类似的方式执行此任务,但使用理解以一种线性格式。
Python3
# Python3 code to demonstrate working of
# Remove keys with substring values
# Using dictionary comprehension + any()
# initializing dictionary
test_dict = {1 : 'Gfg is best for geeks', 2 : 'Gfg is good', 3 : 'I love Gfg'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing substrings
sub_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'}