如何将嵌套字典中的数字字符串转换为对应的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
相关产品推荐
相关产品推荐

