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
rdoesn'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
rdictionary earlier in your code, accidentally removing or overwriting the "followers" key without realizing it.
快速排查与修复方案
先确认
r的真实内容
Add a debug print right before the problematic line to see the full structure ofr: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 directlyr["followers"]).用安全方式访问字典键避免崩溃
Replace direct bracket access with thedict.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)检查数据源的有效性
Ifrcomes 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 assigningrow[x]whenx in u and u[x], so this line doesn't add any value. You can safely remove it.
备注:内容来源于stack exchange,提问作者xdreizein

