Sunday, December 29, 2024
Google search engine
HomeLanguagesPython – Replace None with Empty Dictionary

Python – Replace None with Empty Dictionary

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




# Python3 code to demonstrate working of
# Replace None with Empty Dictionary
# Using recursion + isinstance()
 
# helper function to perform task
 
 
def replace_none(test_dict):
 
    # checking for dictionary and replacing if None
    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])
 
    # checking for list, and testing for each value
    elif isinstance(test_dict, list):
        for val in test_dict:
            replace_none(val)
 
 
# initializing dictionary
test_dict = {"Gfg": {1: None, 7: 4}, "is": None,
             "Best": [1, {5: None}, 9, 3]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# calling helper fnc
replace_none(test_dict)
 
# printing result
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:

  1. Start by creating an empty stack and push the input dictionary onto it.
  2. While the stack is not empty, pop the top item from the stack.
  3. 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.
  4. Repeat steps 2-4 until the stack is empty.
  5. Return the modified dictionary.

Below is the implementation of the above approach:

Python3




def replace_none(test_dict):
    # Create a stack with the initial dictionary
    stack = [test_dict]
     
    # While the stack is not empty, process the dictionaries in the stack
    while stack:
        cur_dict = stack.pop()
        # If the current item in the stack is a dictionary, process its key-value pairs
        if isinstance(cur_dict, dict):
            for key, val in cur_dict.items():
                # If the value is None, replace it with an empty dictionary
                if val is None:
                    cur_dict[key] = {}
                # If the value is a dictionary or a list, push it onto the stack
                elif isinstance(val, (dict, list)):
                    stack.append(val)
        # If the current item in the stack is a list, process its elements
        elif isinstance(cur_dict, list):
            for i, val in enumerate(cur_dict):
                # If the value is None, replace it with an empty dictionary
                if val is None:
                    cur_dict[i] = {}
                # If the value is a dictionary or a list, push it onto the stack
                elif isinstance(val, (dict, list)):
                    stack.append(val)
 
# Example usage
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)

RELATED ARTICLES

Most Popular

Recent Comments