You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将含嵌套字典的字典中的空字符串值替换为None

How to Replace Empty String Values with None in Nested Python Dictionaries

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, key is None, so we set value to 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 with None in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:12:30