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

Python将fpl.json转CSV时遇TypeError:列表索引需为整数而非字典

解决JSON转CSV时的TypeError问题

嘿,我来帮你搞定这个报错!你遇到的TypeError: list indices must be integers, not dict问题,根源是你搞错了循环遍历列表的方式——你的data是一个包含球员字典的列表,但你在循环里错误地把字典当成了列表的索引来使用。

错误原因分析

你代码里的这行:

pp = data [i] ["player_points"]

大概率是因为你的循环写的是for i in data:,这时候i已经是列表里的单个球员字典了,而不是整数索引。你再用data[i]就相当于试图用字典去索引列表,自然会报错。

修正后的完整代码

结合你需要提取的四个字段,我给你写了两种可行的实现方式,选一种用就行:

方式1:使用csv.DictWriter(更简洁,适合字段匹配)

import csv
import json

# 读取JSON文件并解析为球员列表
with open('fpl.json', 'r') as json_file:
    players_list = json.load(json_file)

# 定义要提取的字段(对应CSV表头)
target_fields = ['first_name', 'second_name', 'total_points', 'event_points']

# 写入CSV文件
with open('fpl_players.csv', 'w', newline='') as csv_file:
    # 初始化DictWriter,指定表头字段
    writer = csv.DictWriter(csv_file, fieldnames=target_fields)
    writer.writeheader()  # 写入表头
    
    # 遍历每个球员字典,提取指定字段写入
    for player in players_list:
        writer.writerow({field: player[field] for field in target_fields})

方式2:使用普通csv.writer(手动控制字段顺序)

import csv
import json

with open('fpl.json', 'r') as json_file:
    players_list = json.load(json_file)

# 写入CSV
with open('fpl_players.csv', 'w', newline='') as csv_file:
    writer = csv.writer(csv_file)
    # 先写表头
    writer.writerow(['first_name', 'second_name', 'total_points', 'event_points'])
    
    # 遍历每个球员,按顺序提取字段值
    for player in players_list:
        player_row = [
            player['first_name'],
            player['second_name'],
            player['total_points'],
            player['event_points']
        ]
        writer.writerow(player_row)

关键注意点

  • 确保你的fpl.json确实是一个数组结构(外层是[]),比如示例结构:
    [
      {"first_name": "Petr", "second_name": "Cech", "total_points": 24, "event_points": 0},
      {"first_name": "John", "second_name": "Doe", "total_points": 15, "event_points": 2}
    ]
    
  • 循环时直接遍历列表里的每个字典(用for player in players_list:),而不是试图用索引去取,这样就不会再出现索引类型错误了。

运行修正后的代码,你就能得到预期的CSV输出,比如:

first_name,second_name,total_points,event_points
Petr,Cech,24,0
John,Doe,15,2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:35:04