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

Django出现TypeError:字符串索引必须为整数问题求助

问题:字典访问报错TypeError: string indices must be integers

我尝试存储一个字典数据,但运行代码时遇到了TypeError: string indices must be integers错误,代码里的打印语句看似能输出变量,但实际执行报错。

字典定义

comment = {'en': 'The SIDHistory attribute must be cleared', 'fr': "L'attribut SIDHistory doit être effacé"}

使用的函数代码

if y.get('comment'):
    # print('Comment :')
    comments = y.get('comment')
    print(comments)
    print(comments["en"])
    print(comments["fr"])
    # print('     Comment in English :', comment['en'])
    field_comment_english = comments["en"]
    # print('     Comment in French :', comment['fr'])
    field_comment_french = comments["fr"]
else:
    # print('     Comment in English : None')
    # print('     Comment in French : None')
    field_comment_english = 'None'
    field_comment_french = 'None'

错误信息

File "/Users/cmahouve/PycharmProjects/secad/apps/rules_management/views.py", line 50, in all_rules_interpreter
    print(comments["en"])
TypeError: string indices must be integers

错误原因

报错提示string indices must be integers,说明你通过y.get('comment')拿到的comments不是字典,而是字符串。字符串只能用整数当索引(比如comments[0]取第一个字符),用"en"这种字符串当索引肯定会报错。

你虽然定义了comment字典,但代码里实际操作的是y字典中'comment'对应的值,这说明y['comment']存的不是你定义的那个字典,而是普通字符串。

解决办法

  1. 先确认类型:在comments = y.get('comment')后面加一行代码,打印comments的类型:
    print(type(comments))
    
    如果输出是<class 'str'>,就确认了问题所在。
  2. 修正y的内容:确保y['comment']对应的是你定义的那个包含en和fr键的字典,别把字典转成字符串存进去;如果是从外部(比如JSON文件、接口)读取的,要先把字符串解析成字典(比如用json.loads())。
  3. 加类型校验(可选):为了避免后续踩坑,可以在代码里加类型判断:
    comment_data = y.get('comment')
    if comment_data and isinstance(comment_data, dict):
        comments = comment_data
        # 后续的字典操作
    else:
        field_comment_english = 'None'
        field_comment_french = 'None'
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:06:23