Python - Remove K valued key from Nested Dictionary

Python - Remove K valued key from Nested Dictionary

To remove a key with a specific value from a nested dictionary in Python, you need to recursively traverse the dictionary and remove the key from any sub-dictionaries where it appears. Here is a function that does just that:

def remove_key_recursive(d, key_to_remove, value_to_remove): if isinstance(d, dict): keys_to_delete = [key for key, value in d.items() if key == key_to_remove and value == value_to_remove] for key in keys_to_delete: del d[key] for key, value in d.items(): remove_key_recursive(value, key_to_remove, value_to_remove) # Example usage: nested_dict = { 'level1': { 'level2': { 'k': 5, 'remove_me': 'K_value' }, 'remove_me': 'K_value', 'keep_me': 'other_value' }, 'remove_me': 'K_value' } remove_key_recursive(nested_dict, 'remove_me', 'K_value') print(nested_dict) 

This function remove_key_recursive will remove any key that matches key_to_remove if it also has the value value_to_remove. In the given example, all keys 'remove_me' with the value 'K_value' will be removed from the nested dictionary.

The output will reflect the changes:

{ 'level1': { 'level2': { 'k': 5 }, 'keep_me': 'other_value' } } 

The specified key with the specified value is removed from all levels of the nested dictionary.


More Tags

increment trim imputation gcc spring-data-elasticsearch entity-framework-core-migrations textview google-maps batch-processing stringtokenizer

More Programming Guides

Other Guides

More Programming Examples