Open In App

Python – Removing Nested None Dictionaries

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Records, we can have a problem in which we need to perform the removal of nested records from the dictionary which are empty. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using dict() + filter() This is one of the way in which this task can be performed. In this, we perform the task of filtering the None values using filter(). 

Python3




# Python3 code to demonstrate working of
# Removing Nested None Dictionaries
# Using filter() + dict()
 
# initializing dictionary
test_dict = {'gfg' : {'a': 5}, 'best' : {}, 'for' : {}, 'geeks' : {'b' : 6}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Removing Nested None Dictionaries
# Using filter() + dict()
res = dict(filter(lambda sub: sub[1], test_dict.items()))
 
# printing result
print("The dictionary after filtering is : " + str(res))


Output : 

The original dictionary is : {‘geeks’: {‘b’: 6}, ‘for’: {}, ‘gfg’: {‘a’: 5}, ‘best’: {}} The dictionary after filtering is : {‘geeks’: {‘b’: 6}, ‘gfg’: {‘a’: 5}}

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

  Method #2 : Using dictionary comprehension This is one of the way in which this task can be performed. In this we just recreate the dictionary by checking the value presence of key. 

Python3




# Python3 code to demonstrate working of
# Removing Nested None Dictionaries
# Using dictionary comprehension
 
# initializing dictionary
test_dict = {'gfg' : {'a': 5}, 'best' : {}, 'for' : {}, 'geeks' : {'b' : 6}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Removing Nested None Dictionaries
# Using dictionary comprehension
res = {key : val for key, val in test_dict.items() if val}
 
# printing result
print("The dictionary after filtering is : " + str(res))


Output : 

The original dictionary is : {‘geeks’: {‘b’: 6}, ‘for’: {}, ‘gfg’: {‘a’: 5}, ‘best’: {}} The dictionary after filtering is : {‘geeks’: {‘b’: 6}, ‘gfg’: {‘a’: 5}}

APPROACH 3: USING For 

This code takes a dictionary d as input and recursively removes all nested dictionaries with empty values. It does so by iterating over each key-value pair in the dictionary and recursively calling the function on any nested dictionaries. If the value is empty (e.g. an empty dictionary), it deletes the key from the dictionary. Finally, it returns the modified dictionary.

ALGORITHM:

1. Iterate through each key-value pair in the dictionary.
2. If the value is a dictionary, call the remove_nested_none_dicts function recursively on the value.
3 If the value is None or an empty dictionary, remove the key from the dictionary.
4. Return the modified dictionary.

Python3




def remove_nested_none_dicts(d):
    for k, v in list(d.items()):
        if isinstance(v, dict):
            remove_nested_none_dicts(v)
        if not v:
            del d[k]
    return d
d = {'gfg' : {'a': 5}, 'best' : {}, 'for' : {}, 'geeks' : {'b' : 6}}
print(remove_nested_none_dicts(d))


Output

{'gfg': {'a': 5}, 'geeks': {'b': 6}}

Time complexity: O(nlogn) – where n is the number of keys in the dictionary. The time complexity is O(nlogn) because each recursive call is proportional to the size of the dictionary being passed in. Since each dictionary can have at most n keys, the time complexity is O(nlogn).

Space complexity: O(n) – where n is the number of keys in the dictionary. This is because the recursive function creates a new call stack for each nested dictionary, and the maximum depth of the call stack is proportional to the number of keys in the dictionary. Therefore, the space complexity is O(n).



Last Updated : 27 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads