为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕标琳琳 2022-08-11 17:11:48
Python: 3.x你好。我有下面的csv文件,它有标题和行。行计数可能因文件而异。我正在尝试将此csv转换为字典格式,并且第一行的数据正在重复。"cdrRecordType","globalCallID_callManagerId","globalCallID_callId"1,3,92948991,3,9294933Code: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我不知道我犯了什么错误。有人请帮助纠正它。提前致谢。
查看完整描述

3 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

使用 csv。DictReader

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


查看完整回答
反对 回复 2022-08-11
?
翻翻过去那场雪

TA贡献2065条经验 获得超14个赞

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


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


import csv


with open('example.csv') as csvfile:

    reader = csv.DictReader(csvfile)

    for row in reader:

        print(row)

输出:


$ python3 parse-csv.py

OrderedDict([('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'}


查看完整回答
反对 回复 2022-08-11
?
UYOU

TA贡献1878条经验 获得超4个赞

代码的缩进是错误的。


这两行:


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



查看完整回答
反对 回复 2022-08-11
  • 3 回答
  • 0 关注
  • 299 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号