Python:将 csv 转换为 dict - 使用标题作为键

Mar*_*628 4 python

Python: 3.x

你好。我有下面的 csv 文件,其中有标题和行。行数可能因文件而异。我正在尝试将此 csv 转换为 dict 格式,并且第一行的数据正在重复。

"cdrRecordType","globalCallID_callManagerId","globalCallID_callId"
1,3,9294899
1,3,9294933
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

(通常我的 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'}
Run Code Online (Sandbox Code Playgroud)

print这是内部循环的输出for。最终的输出也是一样的。

我不知道我犯了什么错误。请有人帮忙纠正一下。

提前致谢。

chu*_*ckx 7

您应该使用模块csv而不是手动解析 CSV 文件。

这将导致脚本更简单,并且有助于优雅地处理边缘情况(例如标题行、引用不一致的字段等)。

import csv

with open('example.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row)
Run Code Online (Sandbox Code Playgroud)

输出:

$ python3 parse-csv.py
OrderedDict([('cdrRecordType', '1'), ('globalCallID_callManagerId', '3'), ('globalCallID_callId', '9294899')])
OrderedDict([('cdrRecordType', '1'), ('globalCallID_callManagerId', '3'), ('globalCallID_callId', '9294933')])
Run Code Online (Sandbox Code Playgroud)

如果您打算手动解析,可以采用以下方法:

parsed_list = []
with open('example.csv') as myfile:
    firstline = True
    for line in myfile:
        # Strip leading/trailing whitespace and split into a list of values.
        values = line.strip().split(',')

        # Remove surrounding double quotes from each value, if they exist.
        values = [v.strip('"') for v in values]

        # Use the first line as keys.
        if firstline:
            keys = values
            firstline = False
            # Skip to the next iteration of the for loop.
            continue

        parsed_list.append(dict(zip(keys, values)))

for p in parsed_list:
    print(p)
Run Code Online (Sandbox Code Playgroud)

输出:

$ python3 manual-parse-csv.py
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294899'}
{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294933'}
Run Code Online (Sandbox Code Playgroud)