如何将含重复图片名的CSV转换为指定格式的嵌套字典?
处理CSV文件生成嵌套字典的优化方案
原始CSV数据
| image | id | name | xMin | xMax | yMin | yMax |
|---|---|---|---|---|---|---|
| 858a0246-2f2d-40a9-9bcb-01ab8a93c7f5_BU26844_1630586024_0_6.webp | 1 | Scratch | 604 | 893 | 230 | 413 |
| 858a0246-2f2d-40a9-9bcb-01ab8a93c7f5_BU26844_1630586024_0_6.webp | 2 | Dent | 921 | 1146 | 720 | 857 |
| 858a0246-2f2d-40a9-9bcb-01ab8a93c7f5_BU26844_1630586024_23.webp | 1 | Dent | 343 | 2323 | 334 | 343 |
现有代码及问题
原始代码尝试将CSV读取为以图片名为键的嵌套字典,但生成结果存在两个问题:
- 每条记录中冗余保留了
image字段 - 所有数值类型字段(id、xMin等)均为字符串格式
原始代码:
import csv import itertools import operator import json with open('out1.csv', 'r') as fp: reader = csv.DictReader(fp, dialect='excel', skipinitialspace=True) new_dict = {} for group, records in itertools.groupby(reader, key=operator.itemgetter('image')): new_dict[group] = list(records) json_object = json.dumps(new_dict, indent = 4) print(json_object)
优化后的代码
针对问题,修改代码如下,实现移除冗余字段、转换数值类型的需求:
import csv import itertools import operator import json # 定义需要转换为整数的字段 INT_FIELDS = {'id', 'xMin', 'xMax', 'yMin', 'yMax'} with open('out1.csv', 'r') as fp: reader = csv.DictReader(fp, dialect='excel', skipinitialspace=True) new_dict = {} for image_name, records in itertools.groupby(reader, key=operator.itemgetter('image')): processed_records = [] for record in records: # 移除冗余的image字段 del record['image'] # 转换数值字段为整数 for field in INT_FIELDS: record[field] = int(record[field]) processed_records.append(record) new_dict[image_name] = processed_records json_object = json.dumps(new_dict, indent=4) print(json_object)
期望输出结果
运行优化代码后,将得到如下格式的输出:
{ "858a0246-2f2d-40a9-9bcb-01ab8a93c7f5_BU26844_1630586024_0_6.webp": [ { "id": 1, "name": "Scratch", "xMin": 604, "xMax": 893, "yMin": 230, "yMax": 413 }, { "id": 2, "name": "Dent", "xMin": 921, "xMax": 1146, "yMin": 720, "yMax": 857 } ], "858a0246-2f2d-40a9-9bcb-01ab8a93c7f5_BU26844_1630586024_23.webp": [ { "id": 1, "name": "Dent", "xMin": 343, "xMax": 2323, "yMin": 334, "yMax": 343 } ] }
内容的提问来源于stack exchange,提问作者Alex Bodger
相关产品推荐
相关产品推荐

