猿问

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

Python: 3.x


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


"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'}

这是内部循环的输出。和最终输出也是一样的。printfor


我不知道我犯了什么错误。有人请帮助纠正它。


提前致谢。


慕标琳琳
浏览 301回答 3
3回答

明月笑刀无情

使用 csv。DictReaderimport csv     with open("files\\CUCMdummy.csv", mode='r',newline='\n') as myFile:         reader = list(csv.DictReader(myFile, delimiter=',',quotechar='"'))

翻翻过去那场雪

不应手动解析 CSV 文件,而应使用 csv 模块。这将产生更简单的脚本,并有助于优雅地处理边缘情况(例如标题行,不一致的引号字段等)。import csvwith open('example.csv') as csvfile:    reader = csv.DictReader(csvfile)    for row in reader:        print(row)输出:$ python3 parse-csv.pyOrderedDict([('cdrRecordType', '1'), ('globalCallID_callManagerId', '3'), ('globalCallID_callId', '9294899')])OrderedDict([('cdrRecordType', '1'), ('globalCallID_callManagerId', '3'), ('globalCallID_callId', '9294933')])如果您打算手动解析,可以使用以下方法: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)输出:$ python3 manual-parse-csv.py{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294899'}{'cdrRecordType': '1', 'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294933'}

UYOU

代码的缩进是错误的。这两行:  print(output_dict)  parserd_list.append(output_dict)可以简单地取消缩进,与它们上方的 for 循环位于同一行上。最重要的是,您需要为每个新文件行设置一个新字典。您可以这样做:就在密钥的 for 循环之前。output_dict = {}如上所述,有一些库将使生活更轻松。但是,如果您想坚持追加字典,则可以加载文件的行,将其关闭,然后按如下方式处理行:with open("scratch.txt") as myfile:    data = myfile.readlines()keys = data[0].replace('"','').strip().split(',')output_dicts = []for line in data[1:]:    values = line.strip().split(',')    output_dicts.append(dict(zip(keys, values)))print output_dicts [{'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294899', 'cdrRecordType': '1'}, {'globalCallID_callManagerId': '3', 'globalCallID_callId': '9294933', 'cdrRecordType': '1'}]
随时随地看视频慕课网APP

相关分类

Python
我要回答