You need to enable JavaScript to run this app. Python中如何将键值对字符串转为键值均为int类型的字典
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 02:45:01