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

从字典列表获取字典:更新reps计数报错问题解决

问题解决:将匹配的字典从列表中取出而非得到列表

错误原因

你使用的列表推导式[d for d in objs if d['code'] == comment["code"]]返回的是列表类型——哪怕只有一个匹配的字典,它也会被包裹在列表里。所以直接用obj["reps"]会触发TypeError,因为列表只能用整数或切片作为索引,不能用字符串。

解决方案

方案1:用next()获取匹配的字典(推荐)

把列表推导式改成生成器表达式,通过next()直接取出第一个匹配的字典对象:

for comment in comments:
    if comment["text"] == "a":
        # 取第一个匹配的字典
        obj = next(d for d in objs if d['code'] == comment["code"])
        obj["reps"] += 1

如果要避免因找不到对应code而抛出StopIteration错误,可以添加默认值:

for comment in comments:
    if comment["text"] == "a":
        obj = next((d for d in objs if d['code'] == comment["code"]), None)
        if obj:  # 确认找到对应字典再更新
            obj["reps"] += 1

方案2:直接取列表推导式的第一个元素(适合确定code必存在的场景)

如果能保证每个comment的code在objs中都有对应,可以直接取列表的索引[0]:

for comment in comments:
    if comment["text"] == "a":
        obj = [d for d in objs if d['code'] == comment["code"]][0]
        obj["reps"] += 1

⚠️ 注意:如果没有匹配的code,这种写法会抛出IndexError,不如方案一稳妥。

优化方案:转字典映射提升性能(数据量大时推荐)

如果objs或comments的元素数量较多,每次遍历列表查找效率较低。可以先将objs转换为以code为键的字典,之后查找操作都是O(1)时间复杂度:

# 先构建code到对应字典的映射
obj_map = {item['code']: item for item in objs}

for comment in comments:
    if comment["text"] == "a":
        target_code = comment["code"]
        if target_code in obj_map:
            obj_map[target_code]["reps"] += 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:08:18