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

Python递归实现点分隔字符串转嵌套字典返回None问题排查

问题根因

你的递归构造字典的逻辑本身没有错误,最终拿到None是Python函数返回值的默认规则导致的:

  • 所有Python函数如果没有写显式的return语句,执行完后默认返回None。字典是可变引用类型,递归过程中你确实逐层修改了传入的字典结构,但整个函数没有把构造完成的字典作为返回值传出,你把函数调用结果直接赋值给convertedDict时,拿到的只能是默认的None。
  • 递归调用行stringToJson(dictionary[key], rest)也没有传递返回值,无法把内层构造的结果逐层回传到最外层。
修正方法

两种改法都可以得到预期的嵌套字典,按需选择即可:

方法一:利用字典原地修改特性,不依赖返回值

字典作为可变对象传入函数后,函数内部对它的修改会直接作用在原对象上,不需要接收函数返回值:

import json

test = "fruits.apple.color"
convertedDict = {}

def stringToJson(dictionary, keys):
    if "." in keys:
        key, rest = keys.split(".", 1)
        if key not in dictionary:
            dictionary[key] = {}
        stringToJson(dictionary[key], rest)
    else:
        dictionary[keys] = ''

# 传入初始化好的字典,函数执行完后字典已经被修改为目标结构
stringToJson(convertedDict, test)
print(convertedDict)
# 后续转JSON直接调用 json.dumps(convertedDict, indent=2) 即可

运行输出:

{'fruits': {'apple': {'color': ''}}}

方法二:补全返回值逻辑,直接返回构造完成的字典

如果你希望函数调用后直接返回最终字典,只需要在两个逻辑分支的末尾加上return语句,把当前层处理完的字典返回即可:

import json

test = "fruits.apple.color"

def stringToJson(dictionary, keys):
    if "." in keys:
        key, rest = keys.split(".", 1)
        if key not in dictionary:
            dictionary[key] = {}
        stringToJson(dictionary[key], rest)
        return dictionary
    else:
        dictionary[keys] = ''
        return dictionary

convertedDict = stringToJson({}, test)
print(convertedDict)

运行结果和方法一完全一致。


内容的提问来源于stack exchange,提问作者João Pedro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 10:33:11