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

Python字典操作及KeyError('followers')报错问题咨询

Python字典操作及KeyError('followers')报错问题咨询

Hey there, let's break down why you're hitting this KeyError('followers') issue step by step:

直接原因

This error pops up because the dictionary r you're trying to access doesn't have a key named "followers". When you run for u in r["followers"], Python can't locate that key in r and throws an error as a result.

可能的触发场景

  • The data source (like an API response or JSON file) providing r doesn't include the "followers" field at all. Maybe the API returned an error response instead of the data you expected, or your request parameters were incorrect.
  • You might have modified the r dictionary earlier in your code, accidentally removing or overwriting the "followers" key without realizing it.

快速排查与修复方案

  1. 先确认r的真实内容
    Add a debug print right before the problematic line to see the full structure of r:

    import pprint
    pprint.pprint(r)  # 清晰展示字典的所有键值对
    for u in r["followers"]:
        # 后续代码...
    

    This will help you confirm if "followers" is truly missing, or if it's nested under another key (like r["data"]["followers"] instead of directly r["followers"]).

  2. 用安全方式访问字典键避免崩溃
    Replace direct bracket access with the dict.get() method, which lets you set a default value if the key doesn't exist. This way your code won't crash even if "followers" is missing:

    # 若"followers"不存在,返回空列表避免循环报错
    for u in r.get("followers", []):
        with open(r'data.csv', 'a', encoding="utf-8") as f:
            row = {}
            for x in fieldnames:
                if x in u and u[x]:
                    row[x] = str(u[x])
            # 初始化DictWriter并写入行
            writer = csv.DictWriter(
                f, fieldnames=fieldnames, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
            writer.writerow(row)
    
  3. 检查数据源的有效性
    If r comes from an API call, verify the HTTP status code (make sure it's 200 OK) and cross-reference the API documentation to confirm the expected response structure. Sometimes APIs return error objects (like {"error": "Invalid token"}) when something goes wrong, which won't contain the "followers" key.

小优化建议

  • You're opening the CSV file inside the loop, which is inefficient. Move the file opening outside the loop to reduce repeated I/O operations:
    with open(r'data.csv', 'a', encoding="utf-8") as f:
         writer = csv.DictWriter(
             f, fieldnames=fieldnames, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
         for u in r.get("followers", []):
             row = {}
             for x in fieldnames:
                 if x in u and u[x]:
                     row[x] = str(u[x])
             writer.writerow(row)
    
  • The line if x == "uid": row[x] = str(u[x]) + '' is redundant—you already handle assigning row[x] when x in u and u[x], so this line doesn't add any value. You can safely remove it.

备注:内容来源于stack exchange,提问作者xdreizein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 08:42:45