CSV文件处理:将两行CSV数据转为指定格式字典的技术问题
CSV转字典并输出正确格式问题解决
需求说明
编写程序接收CSV文件名输入(如"input1.csv"),该文件包含两行逗号分隔值。需使用内置csv模块的open()和reader()方法,将每行的逗号分隔值转换为键值对字典,最终输出如下格式的两个字典:
{'key': 'value', 'key': 'value', 'key': 'value'} {'key': 'value', 'key': 'value', 'key': 'value'}
原代码问题
你尝试的代码存在两个主要问题:
- 第二行字典的构建逻辑错误,遍历
create_list会导致索引操作报错 - 手动拼接输出字符串时未给键值添加引号,导致输出不符合要求的字典格式
原代码:
import csv # file_name = input() dict_1 = {} dict_2 = {} file = open('input1.csv', 'r') content = csv.reader(file) create_list = [] for line in content: create_list.append(line) file.close() # Create the dictionary from the _list for the first row... for i in range(0, len(create_list[0]), 2): dict_1[create_list[0][i]] = create_list[0][i + 1] # Create the dictionary from the _list for the second row... for i in create_list: dict_2[create_list[1][i]] = create_list[1][i + 1] # Print the first dictionary as per the required format... print("{", end="") for key, val in dict_1.items(): if val != create_list[0][-1]: print("{}:{}".format(key, val), end=',') else: print("{}:{}".format(key, val), end='}') # Print the second dictionary as per the required format... print("\n{", end="") for key, val in dict_2.items(): if val != create_list[1][-1]: print("{}:{}".format(key, val), end=',') else: print("{}:{}".format(key, val), end='}')
修正后的解决方案
代码实现
import csv def row_to_dict(row): """将一行按两两分组转换为字典""" return {row[i]: row[i+1] for i in range(0, len(row), 2)} # 接收文件名输入 file_name = input() # 使用with语句自动管理文件,无需手动close with open(file_name, 'r') as f: # 读取所有行到列表 rows = list(csv.reader(f)) # 确保文件至少有两行数据 if len(rows) >= 2: dict1 = row_to_dict(rows[0]) dict2 = row_to_dict(rows[1]) # 直接打印字典即可得到要求的格式 print(dict1) print(dict2) else: print("文件行数不足,需要至少两行数据")
关键修正点
- 修复字典构建逻辑:用列表推导式按步长2遍历行元素,统一处理两行的字典转换,避免索引错误
- 简化文件操作:使用
with语句自动关闭文件,更安全简洁 - 正确输出格式:直接打印字典对象,Python会自动以
{'key': 'value'}的格式输出,无需手动拼接字符串
内容的提问来源于stack exchange,提问作者teddy
相关产品推荐
相关产品推荐

