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

Python列表元素关联同名字典遇TypeError问题求助

问题解决:字符串索引错误的原因与修复

错误原因

你在business列表里存的是字符串(比如'accounting'),而非对应的字典对象。循环时each拿到的是字符串,而字符串只能用整数作为索引,因此执行each['regex']会触发TypeError: string indices must be integers, not 'str'。

修复方法

方法1:用总字典统一管理业务字典(推荐)

把所有业务相关的字典放到一个总字典中,通过字符串键直接关联对应字典,代码更规范易维护:

# 定义各业务字典
accounting = {'regex': 'blah|something', 'filename': 'somefile'}
it = {'regex': 'it-regex', 'filename': 'it-file'}
security = {'regex': 'sec-regex', 'filename': 'sec-file'}

# 总字典关联业务名称与对应字典
business_map = {
    'accounting': accounting,
    'it': it,
    'security': security
}

business = ['accounting', 'it', 'security']
for name in business:
    rx = business_map[name]['regex']
    print(rx)  # 依次输出对应字典的regex值

方法2:通过globals()获取全局变量(仅临时测试用)

如果不想额外创建总字典,可以用globals()函数获取全局变量字典,通过字符串键取出同名字典,但这种方式依赖全局变量,不推荐用于正式代码:

accounting = {'regex': 'blah|something', 'filename': 'somefile'}
it = {'regex': 'it-regex', 'filename': 'it-file'}
security = {'regex': 'sec-regex', 'filename': 'sec-file'}

business = ['accounting', 'it', 'security']
for name in business:
    rx = globals()[name]['regex']
    print(rx)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:22:37