Python – 用空字典替换 None
给定一个字典,用空字典替换每个嵌套中的 None 值。
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.
方法:使用递归+ isinstance()
在此,我们使用 isinstance() 检查字典实例并调用嵌套字典替换的递归。这还会检查列表元素形式的嵌套实例,并使用 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))
输出:
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]}