Monday, June 15, 2026
HomeLanguagesPython – Remove unwanted Keys associations

Python – Remove unwanted Keys associations

Sometimes, while working with Python dictionaries, we can have problem in which we need to remove some unwanted keys and its associated nestings. This can have application across many domains including web development and competitive programming. Let’s discuss certain ways in which this task can be performed.

Input : test_dict = {‘best’ : {‘for’ : {‘neveropen’ : {‘CS’ : {‘Gfg’ : 12}}}}}
Output : {‘best’: {‘for’: {}}}

Input : test_dict = {‘best’ : 14, ‘gfg’ : 13}
Output : {‘best’ : 14, ‘gfg’ : 13}

Method #1 : Using isinstance() + loop + recursion
The combination of above functionalities can be used to solve this problem. In this, we check for the element value being a dictionary or key using isinstance() and we recur for the construction of all the keys that are not present as unwanted keys.




# 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' : {'neveropen' :  {'CS' : 12}}}}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# initializing unwanted keys
unw_keys = ['is', 'neveropen']
  
# Remove unwanted Keys associations
# Using isinstance() + loop + recursion
res = helper_fnc(test_dict, unw_keys)
      
# printing result 
print("The filtered dictionary : " + str(res)) 


Output :

The original dictionary : {‘Gfg’: {‘is’: 45, ‘good’: 15}, ‘best’: {‘for’: {‘neveropen’: {‘CS’: 12}}}}
The filtered dictionary : {‘Gfg’: {‘good’: 15}, ‘best’: {‘for’: {}}}

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS