如何创建可被另一CSV指令调用的列表并构建配置文件字典
解决CSV转字典及跨文件数据调用问题
需求说明
我有两个CSV文件:
profiles.csv:存储配置文件信息,每行以PROFILE_NAME标识,需要转成以PROFILE_NAME为键的字典,格式示例:profiles = {"profile1": ["item"]},每个键对应的值是该行的信息列表。instructions.csv:需要能调用上述字典中的配置信息。
CSV示例
profiles.csv
PROFILE_NAME,FIRST_NAME,LAST_NAME Profile1,John,Doe Profile2,Jane,Deere
instructions.csv
PROFILE_NAME,JOB,HOURS Profile1,Mechanic,50 Profile2,Cook,65
问题分析与代码修正
你提供的代码存在一个小错误:CSV表头是FIRST_NAME和LAST_NAME,但代码里写的是row['FIRSTNAME']和row['LASTNAME'](缺少下划线),这会触发KeyError。另外,我们还需要处理instructions.csv,实现它对profiles数据的调用。
修正后的profiles处理代码
import csv def load_profiles(): file = "profiles.csv" profiles = {} with open(file, mode='r', newline='', encoding='utf-8') as f: reader = csv.DictReader(f) for row in reader: name = row['PROFILE_NAME'] # 匹配CSV表头正确取值,组成列表 profiles[name] = [ row['FIRST_NAME'], row['LAST_NAME'] ] return profiles
处理instructions并关联profiles数据
要让instructions的指令调用profiles信息,可以先加载profiles字典,再遍历instructions.csv并结合两者数据:
def load_instructions_with_profiles(profiles_dict): file = "instructions.csv" linked_data = {} with open(file, mode='r', newline='', encoding='utf-8') as f: reader = csv.DictReader(f) for row in reader: profile_name = row['PROFILE_NAME'] # 从profiles字典获取对应信息,不存在则用默认值 profile_info = profiles_dict.get(profile_name, ["未知姓名", "未知姓氏"]) # 按需组合instructions与profiles的数据格式 linked_data[profile_name] = { "基础信息": profile_info, "职业": row['JOB'], "工作时长": int(row['HOURS']) } return linked_data # 使用示例 if __name__ == "__main__": profiles = load_profiles() print("加载后的profiles字典:") print(profiles) # 输出: {'Profile1': ['John', 'Doe'], 'Profile2': ['Jane', 'Deere']} combined_data = load_instructions_with_profiles(profiles) print("\n关联后的指令与配置数据:") print(combined_data) # 输出: {'Profile1': {'基础信息': ['John', 'Doe'], '职业': 'Mechanic', '工作时长': 50}, ...}
关键注意点
- 确保CSV表头和代码中取值的键完全一致,避免键不存在的报错。
- 使用
csv.DictReader可以直接通过表头名获取列值,比索引取值更直观易维护。 - 用
dict.get()方法获取profiles数据,能处理不存在的PROFILE_NAME情况,避免程序崩溃。
内容的提问来源于stack exchange,提问作者drag6ter
相关产品推荐
相关产品推荐

