Python中如何将键值对字符串转为键值均为int类型的字典
实现方法
方案1:基于原有代码修改
仅需在拆分处理步骤增加int类型转换即可:
test_str = '1:20,3:4,5:30' res = [] for sub in test_str.split(','): if ':' in sub: k, v = map(str.strip, sub.split(':', 1)) res.append((int(k), int(v))) res = dict(res) print(res) # 输出结果:{1: 20, 3: 4, 5: 30}
方案2:字典推导式简化写法
可以用推导式简化代码逻辑,一行即可完成转换:
test_str = '1:20,3:4,5:30' res = {int(k.strip()): int(v.strip()) for k, v in (sub.split(':', 1) for sub in test_str.split(',') if ':' in sub)} print(res)
方案3:增加异常兼容逻辑
如果输入字符串可能存在非数字格式的非法键值对,可以加校验逻辑避免抛出异常,同时过滤无效内容:
test_str = '1:20,3:4,5:30,abc:12,6:xyz' res = [] for sub in test_str.split(','): if ':' in sub: k, v = map(str.strip, sub.split(':', 1)) # 仅处理键和值都是纯数字的项 if k.isdigit() and v.isdigit(): res.append((int(k), int(v))) res = dict(res) print(res) # 输出结果:{1: 20, 3: 4, 5: 30}
内容的提问来源于stack exchange,提问作者user1298426
相关产品推荐
相关产品推荐

