如何将Python字典中的字符串格式数组转换为对应的整数数组
Python字典值(字符串数组转整数数组)转换方法
方案1:使用ast.literal_eval(最推荐,安全无注入风险)
ast.literal_eval是Python官方内置的字面量解析工具,只会解析合法的Python基础数据结构,不会执行任意代码,安全性远高于eval,完全适配你给出的场景:
import ast # 输入的原始字典 str_arr_dict = { 1: '[8, 9, 10, 11, 12, 13, 14, 15, 16]', 2: '[17, 18, 19, 20, 21, 22, 23]', 3: '[1, 2, 3, 4, 5, 6, 7]', 4: '[24, 25, 26]' } # 一行完成转换 int_arr_dict = {key: ast.literal_eval(value) for key, value in str_arr_dict.items()}
转换后int_arr_dict就是你需要的、值为整数数组的字典。
方案2:手动字符串处理(无导入依赖场景可用)
如果你的使用场景不希望导入额外模块,可以直接对字符串做裁剪、分割、类型转换处理:
str_arr_dict = { 1: '[8, 9, 10, 11, 12, 13, 14, 15, 16]', 2: '[17, 18, 19, 20, 21, 22, 23]', 3: '[1, 2, 3, 4, 5, 6, 7]', 4: '[24, 25, 26]' } int_arr_dict = {} for key, str_val in str_arr_dict.items(): # 去除首尾方括号,按逗号分割后去除空格,逐个转整数 num_list = [int(num.strip()) for num in str_val.strip('[]').split(',')] int_arr_dict[key] = num_list
如果原始字符串中存在非数字字符,两种方案都会抛出异常,生产环境使用前建议补充异常捕获逻辑做数据校验。
内容的提问来源于stack exchange,提问作者Chandu
相关产品推荐
相关产品推荐

