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
# 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:
- 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):
# 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)
Similar Reads
Python - Replace Non-None with K Sometimes, while working with Python lists we can have a problem in which we need to perform the replacement of all the elements that are non-None. This kind of problem can have applications in many domains such as web development and day-day programming. Let's discuss certain ways in which this tas
6 min read
Python | Initialize dictionary with None values Sometimes, while working with dictionaries, we might have a utility in which we need to initialize a dictionary with None values so that they can be altered later. This kind of application can occur in cases of memoization in general or competitive programming. Let's discuss certain ways in which th
4 min read
Python - Removing Nested None Dictionaries 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() + filte
4 min read
Python - Test for Empty Dictionary Value List Given a dictionary with list as values, check if all lists are empty. Input : {"Gfg" : [], "Best" : []} Output : True Explanation : Both lists have no elements, hence True. Input : {"Gfg" : [], "Best" : [4]} Output : False Explanation : "Best" contains element, Hence False. Method #1 : Using any() +
6 min read
Python Remove Dictionary Item Sometimes, we may need to remove a specific item from a dictionary to update its structure. For example, consider the dictionary d = {'x': 100, 'y': 200, 'z': 300}. If we want to remove the item associated with the key 'y', several methods can help achieve this. Letâs explore these methods.Using pop
2 min read
Python | Initialize list with empty dictionaries While working with Python, we can have a problem in which we need to initialize a list of a particular size with empty dictionaries. This task has it's utility in web development to store records. Let's discuss certain ways in which this task can be performed. Method #1 : Using {} + "*" operator Thi
5 min read
Python - Convert None to empty string In Python, it's common to encounter None values in variables or expressions. In this article, we will explore various methods to convert None into an empty string.Using Ternary Conditional OperatorThe ternary conditional operator in Python provides a concise way to perform conditional operations wit
2 min read
Remove Spaces from Dictionary Keys - Python Sometimes, the keys in a dictionary may contain spaces, which can create issues while accessing or processing the data. For example, consider the dictionary d = {'first name': 'Nikki', 'last name': 'Smith'}. We may want to remove spaces from the keys to standardize the dictionary, resulting in {'fir
3 min read
Python - Remove Top level from Dictionary Sometimes, while working with Python Dictionaries, we can have nesting of dictionaries, with each key being single values dictionary. In this we need to remove the top level of dictionary. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed.
3 min read
Python - Create a Dictionary using List with None Values The task of creating a dictionary from a list of keys in Python involves transforming a list of elements into a dictionary where each element becomes a key. Each key is typically assigned a default value, such as None, which can be updated later. For example, if we have a list like ["A", "B", "C"],
3 min read