Python – 删除不需要的键关联
有时,在使用Python字典时,我们可能会遇到需要删除一些不需要的键及其相关嵌套的问题。这可以跨许多领域应用,包括 Web 开发和竞争性编程。让我们讨论可以执行此任务的某些方式。
Input : test_dict = {‘best’ : {‘for’ : {‘geeks’ : {‘CS’ : {‘Gfg’ : 12}}}}}
Output : {‘best’: {‘for’: {}}}
Input : test_dict = {‘best’ : 14, ‘gfg’ : 13}
Output : {‘best’ : 14, ‘gfg’ : 13}
方法 #1:使用isinstance()
+ 循环 + 递归
上述功能的组合可以用来解决这个问题。在此,我们使用 isinstance() 检查元素值是否为字典或键,并重复构造所有不作为不需要的键存在的键。
# Python3 code to demonstrate working of
# Remove unwanted Keys associations
# Using isinstance() + loop + recursion
def helper_fnc(test_dict, unw_keys):
temp = {}
for key, val in test_dict.items():
if key in unw_keys:
continue
if isinstance(val, dict):
temp[key] = helper_fnc(val, unw_keys)
else:
temp[key] = val
return temp
# initializing dictionary
test_dict = {"Gfg" : {'is' : 45, 'good' : 15},
'best' : {'for' : {'geeks' : {'CS' : 12}}}}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing unwanted keys
unw_keys = ['is', 'geeks']
# Remove unwanted Keys associations
# Using isinstance() + loop + recursion
res = helper_fnc(test_dict, unw_keys)
# printing result
print("The filtered dictionary : " + str(res))
输出 :
The original dictionary : {‘Gfg’: {‘is’: 45, ‘good’: 15}, ‘best’: {‘for’: {‘geeks’: {‘CS’: 12}}}}
The filtered dictionary : {‘Gfg’: {‘good’: 15}, ‘best’: {‘for’: {}}}