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

如何将含非唯一路径的CSV行转换为指定字典格式?

解决CSV转字典时重复路径下多图片的存储问题

你的核心问题是原代码中直接用my_dict[img_path]=img_name赋值,导致同一路径下的新图片名覆盖旧值,无法累积多个图片名。以下是修正后的方案:

方案一:基础字典判断写法

直接检查字典中是否已存在目标路径,不存在则初始化列表,存在则追加图片名:

import csv
import os

my_dict = {}

with open("my_csv.csv", 'r') as file:
    csvreader = csv.reader(file)
    for row in csvreader:
        for rw in row:  
            img_path, img_name = os.path.split(rw)
            # 初始化列表或追加元素
            if img_path not in my_dict:
                my_dict[img_path] = []
            my_dict[img_path].append(img_name)

print(my_dict)

方案二:用defaultdict简化代码

借助collections.defaultdict可以自动为不存在的键初始化列表,让代码更简洁:

import csv
import os
from collections import defaultdict

my_dict = defaultdict(list)

with open("my_csv.csv", 'r') as file:
    csvreader = csv.reader(file)
    for row in csvreader:
        for rw in row:  
            img_path, img_name = os.path.split(rw)
            my_dict[img_path].append(img_name)

# 可选:转换为普通字典(如果不需要defaultdict特性)
my_dict = dict(my_dict)
print(my_dict)

两种方案运行后都能得到你期望的输出结构:

{
  'folder/1/img/file/1.mp3': ['4.jpg','8.jpg'],
  'folder/3/img/file/3.mp3': ['1.jpg','5.jpg'],
  'folder/6/img/file/6.mp3': ['6.jpg','8.jpg'],
  'folder/7/img/file/7.mp3': ['9.jpg']
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:45:52