Python – Replace None with Empty Dictionary
Last Updated :
10 Apr, 2023
Given a dictionary, replace None values in every nesting with an empty dictionary.
Input : test_dict = {“Gfg” : {1 : None, 7 : None}, “is” : None, “Best” : [1, { 5 : None }, 9, 3]}
Output : {‘Gfg’: {1: {}, 7: {}}, ‘is’: {}, ‘Best’: [1, {5: {}}, 9, 3]}
Explanation : All None values are replaced by empty dictionaries.
Input : test_dict = {“Gfg” : {7 : None}, “is” : None, “Best” : [1, { 5 : None }, 9, 3]}
Output : {‘Gfg’: {7: {}}, ‘is’: {}, ‘Best’: [1, {5: {}}, 9, 3]}
Explanation : All None values are replaced by empty dictionaries.
Method : Using recursion + isinstance()
In this, we check for dictionary instance using isinstance() and call for recursion for nested dictionary replacements. This also checks for nested instances in form of list elements and checks for the list using isinstance().
Python3
def replace_none(test_dict):
if isinstance (test_dict, dict ):
for key in test_dict:
if test_dict[key] is None :
test_dict[key] = {}
else :
replace_none(test_dict[key])
elif isinstance (test_dict, list ):
for val in test_dict:
replace_none(val)
test_dict = { "Gfg" : { 1 : None , 7 : 4 }, "is" : None ,
"Best" : [ 1 , { 5 : None }, 9 , 3 ]}
print ( "The original dictionary is : " + str (test_dict))
replace_none(test_dict)
print ( "The converted dictionary : " + str (test_dict))
|
Output:
The original dictionary is : {‘Gfg’: {1: None, 7: 4}, ‘is’: None, ‘Best’: [1, {5: None}, 9, 3]} The converted dictionary : {‘Gfg’: {1: {}, 7: 4}, ‘is’: {}, ‘Best’: [1, {5: {}}, 9, 3]}
Method 2: Using stack
Step-by-step approach:
- Start by creating an empty stack and push the input dictionary onto it.
- While the stack is not empty, pop the top item from the stack.
- If the popped item is a dictionary, loop through its key-value pairs:
a. If the value is None, replace it with an empty dictionary.
b. If the value is a dictionary or a list, push it onto the stack.
If the popped item is a list, loop through its elements:
a. If the element is None, replace it with an empty dictionary.
b. If the element is a dictionary or a list, push it onto the stack.
- Repeat steps 2-4 until the stack is empty.
- Return the modified dictionary.
Below is the implementation of the above approach:
Python3
def replace_none(test_dict):
stack = [test_dict]
while stack:
cur_dict = stack.pop()
if isinstance (cur_dict, dict ):
for key, val in cur_dict.items():
if val is None :
cur_dict[key] = {}
elif isinstance (val, ( dict , list )):
stack.append(val)
elif isinstance (cur_dict, list ):
for i, val in enumerate (cur_dict):
if val is None :
cur_dict[i] = {}
elif isinstance (val, ( dict , list )):
stack.append(val)
test_dict = { "Gfg" : { 1 : None , 7 : 4 }, "is" : None , "Best" : [ 1 , { 5 : None }, 9 , 3 ]}
replace_none(test_dict)
print (test_dict)
|
Output
{'Gfg': {1: {}, 7: 4}, 'is': {}, 'Best': [1, {5: {}}, 9, 3]}
Time complexity: O(n)
Auxiliary space: O(n)
Share your thoughts in the comments
Please Login to comment...