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

Python检查字典key存在报TypeError: string indices must be integers如何解决

问题解决:Python校验字典键时报TypeError错误

错误原因

直接遍历Python字典时,默认遍历对象是字典的所有键,你给出的store_group_details字典的键均为字符串类型,代码中对字符串执行detais['type']这类字典式下标访问操作,不符合字符串的索引规则,因此触发string indices must be integers报错。
同时你的需求是校验用户输入是否匹配字典的键,不需要额外遍历,直接用字典的成员判断语法即可实现。

修复方案

最优写法(无需遍历)

def update_details():
    # 修正原代码的拼写错误:feild→field、detais→details
    input_details = input("please select which field you want to change ")   
    if input_details in store_group_details:
        print("exist")
    else:
        print("not exist")

遍历写法(如需额外处理键对应的值时使用)

如果后续需要同步操作匹配键对应的数值,可以采用遍历键值对的写法:

def update_details():
    input_details = input("please select which field you want to change ")   
    for key, val in store_group_details.items():
        if key == input_details:
            print("exist")
            # 此处可添加对val的操作逻辑
            break
    else:
        print("not exist")

内容的提问来源于stack exchange,提问作者Mona Salih

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:24:06