如何在Python中将含嵌套字典的字典中的空字符串值替换为None
Got it, let's tackle this problem: replacing every empty string ("") with None in a Python dictionary that supports nested dictionaries (even empty dicts as values). Here's a solid recursive solution that handles all levels of nesting perfectly.
First, here's the test dictionary we'll use to validate the solution:
test_dict = { 'hi': {'h': '', 'i': 'i'}, 'bye': {}, 'sth': '' }
Recursive Implementation
This function works by digging into every level of the dictionary, so it handles nested structures seamlessly:
def empty_str_value_to_none(parent_dict, key=None): if key is not None: value = parent_dict[key] else: value = parent_dict if type(value) == dict: for sub_key in value: empty_str_value_to_none(value, sub_key) elif value == "": parent_dict[key] = None
How the Logic Works
Let's break down what's happening step by step:
- When we first call the function with just the top-level dictionary,
keyisNone, so we setvalueto the entire dictionary itself. - If the current value is a dictionary (whether it's the top-level one or a nested child dict), we loop through each of its keys and recursively call the function to process each value.
- If we hit an empty string (
""), we directly replace that value withNonein the original dictionary (this is an in-place modification—the original dict gets updated instead of creating a new copy).
Test the Solution
Run the function and print the result to confirm it works as expected:
empty_str_value_to_none(test_dict) print(test_dict)
Output
{'hi': {'h': None, 'i': 'i'}, 'bye': {}, 'sth': None}
All empty strings are replaced with None, while nested dictionaries and non-empty values remain untouched—exactly what we need.
内容的提问来源于stack exchange,提问作者Leyla Krz

