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

Python解析plist空字段报TypeError: string indices must be integers如何解决

报错原因
  1. 直接触发点是字典推导式中的v["dict"]操作:当cast、导演等字段无数据时,zip(dict["key"], dict["array"])拿到的v不是预期的包含dict键的字典,而是字符串类型(大概率是空字符串"")。字符串使用["dict"]这种字典键方式取值时,就会触发string indices must be integers类型错误。
  2. 现有get_plist_names函数也存在容错漏洞:如果传入的参数不是预期的列表/包含string键的字典,后续执行也会触发同类错误。
  3. 额外隐患:你的代码里用了内置关键字dict作为变量名,会覆盖Python原生字典类,容易引发其他隐性问题。
修复方案

可以从两处加容错逻辑,确保空字段直接跳过,程序正常运行:

第一步:加固get_plist_names函数的类型校验

def get_plist_names(name_dict):
    res = []
    # 统一转为可迭代对象
    iter_obj = name_dict if isinstance(name_dict, list) else [name_dict]
    for o in iter_obj:
        # 仅处理符合格式的元素,不符合直接跳过
        if isinstance(o, dict) and "string" in o:
            res.append(o["string"])
    return res

第二步:调整字段解析逻辑,增加类型判断

plist_metadata = json.loads(dump_json)
# 不要用dict当变量名,避免覆盖内置类
plist_dict = plist_metadata['plist']['dict']
zipped = zip(plist_dict["key"], plist_dict["array"])

extra_dict = {}
for k, v in zipped:
    # 仅当v是字典且包含dict键时才处理,其他情况直接跳过
    if isinstance(v, dict) and "dict" in v:
        extra_dict[k] = get_plist_names(v["dict"])

result = {"cast": [], "directors": [], "screenwriters": [], "producers": []} | extra_dict

# get默认值改为空列表,和前面的默认值格式统一,避免join异常
cast_value = ', '.join(result.get("cast", []))
directors_value = ', '.join(result.get("directors", []))
producers_value = ', '.join(result.get("producers", []))
screenwriters_value = ', '.join(result.get("screenwriters", []))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 04:15:04