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

如何将嵌套字典中的数字字符串转换为对应的int类型数值

嵌套字典数字字符串转int实现方案

直接写一个递归处理函数即可,兼容任意层级的嵌套字典:

def convert_numeric_str_to_int(data):
    if isinstance(data, dict):
        return {key: convert_numeric_str_to_int(value) for key, value in data.items()}
    if isinstance(data, str):
        try:
            return int(data)
        except ValueError:
            return data
    return data

使用示例

d = {'word': {'word1': '1', 'word2': '-1', 'word3': '2'}}
result = convert_numeric_str_to_int(d)
print(result)
# 输出结果:{'word': {'word1': 1, 'word2': -1, 'word3': 2}}

说明

  • 仅会转换能正常解析为整数的字符串,不符合整数格式的字符串会原样返回,不会抛出异常
  • 支持任意深度的嵌套字典结构,不需要提前适配你的字典层级
  • 如果需要同时支持浮点数转换,可在异常捕获前增加float转换逻辑即可

内容的提问来源于stack exchange,提问作者christmas.tree

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:36:04