Python: 3.x
您好。我有一个包含标题和行的CSV文件,行数可能因文件而异。我正在尝试将此CSV转换为字典格式,但第一行的数据重复出现。
"cdrRecordType","globalCallID_callManagerId","globalCallID_callId"
1,3,9294899
1,3,9294933
代码:
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来去除双引号。
输出结果如下:
{'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'}
这是在 for
循环中使用 print
的输出结果。最终的输出结果也是一样的。
我不知道我犯了什么错误。请有人帮忙纠正一下。
提前感谢。
output_dict = {}
直接移动到for n in range(len(mykeys)):
循环之前。此外,你应该在这个循环之后将字典添加到列表中,而不是在每次迭代中添加。 - Michael Butscheroutput_dict[mykeys[n]...
移出 for 循环,而是将字典添加到列表中。 - Michael Butscher