Python实现CSV转JSON按相同键值分组的代码修改求助
解决CSV转JSON的分组需求
你的核心需求是按Area字段分组,将同一Area下的Employee合并为数组。可以通过以下修改实现:
修改后的代码:
import csv import json from collections import defaultdict def csv_to_json(csvFilePath, jsonFilePath): # 用字典按Area分组,key是Area名称,value是员工列表 area_groups = defaultdict(list) with open(csvFilePath, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) for row in csvReader: area = row['Area'] employee = row['Employee'] # 将员工添加到对应Area的列表中 area_groups[area].append(employee) # 将分组后的字典转换为期望的JSON数组格式 jsonArray = [] for area, employees in area_groups.items(): jsonArray.append({ "Area": area, "Employee": employees }) with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: jsonString = json.dumps(jsonArray, indent=4) jsonf.write(jsonString) csvFilePath='example.csv' jsonFilePath='output.json' csv_to_json(csvFilePath, jsonFilePath)
关键修改说明:
- 使用
collections.defaultdict(list)创建分组字典,自动为每个新Area初始化空列表,简化判断逻辑 - 遍历CSV行时,提取Area和Employee,将员工追加到对应Area的列表中
- 最后将分组字典转换为你需要的数组结构,每个元素包含Area字段和对应的Employee数组
如果不想引入collections模块,也可以用普通字典实现:
# 替换area_groups的初始化和遍历逻辑 area_groups = {} for row in csvReader: area = row['Area'] employee = row['Employee'] if area not in area_groups: area_groups[area] = [] area_groups[area].append(employee)
运行修改后的代码,就能得到你期望的JSON输出。
内容的提问来源于stack exchange,提问作者Mauricio Reyes
相关产品推荐
相关产品推荐

