python - Python:将 csv 转换为 dict - 使用标题作为键
问题描述
Python: 3.x
你好。我有下面的 csv 文件,它有标题和行。行数可能因文件而异。我正在尝试将此 csv 转换为 dict 格式,并且第一行正在重复数据。
"cdrRecordType","globalCallID_callManagerId","globalCallID_callId"
1,3,9294899
1,3,9294933
Code:
parserd_list = []
output_dict = {}
with open("files\\CUCMdummy.csv") as myfile:
firstline = True
for line in myfile:
if firstline:
mykeys = ''.join(line.split()).split(',')
firstline = False
else:
values = ''.join(line.split()).split(',')
for n in range(len(mykeys)):
output_dict[mykeys[n].rstrip('"').lstrip('"')] = values[n].rstrip('"').lstrip('"')
print(output_dict)
parserd_list.append(output_dict)
#print(parserd_list)
(通常我的 csv 列数超过 20,但我提供了一个示例文件。)
(我使用 rstrip/lstrip 来去掉双引号。)
Output getting:
{'cdrRecordType': '1'}
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3'}
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294899'}
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294899'}
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294899'}
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294933'}
这是print
内部for
循环的输出。和最终的输出也是一样的。
我不知道我在做什么错误。有人请帮助纠正它。
提前致谢。
解决方案
使用 csv.DictReader
import csv
with open("files\\CUCMdummy.csv", mode='r',newline='\n') as myFile:
reader = list(csv.DictReader(myFile, delimiter=',',quotechar='"'))
推荐阅读
- image - 当我在渲染 HTML 后按下它时,不要在浏览器中显示图像
- java - 请检查我想使用的代码,而当用户在第一次输入中输入 0 时条件必须停止
- mysql - 数据库设计:每位用户每天的价值
- karma-jasmine - Angular cli 业力不能使用 json 文件
- github - Google CloudBuild 不会获取具有大型 monorepo 的最新提交和分支
- javascript - 如何将嵌套子数组转换为重定向/面包屑?
- android - Android 为提示文本设置填充
- sql-server - 在另一个表中查找具有匹配记录的记录
- java - AlarmManager 未触发 AlarmNotificationReceiver
- angular - Angular 在鼠标移动时不断评估 ngStyle 表达式