在python中,将一列有序字典写入csv文件

2024-05-23 17:42:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经点了很多东西

[OrderedDict([('mnemonic', 'VERS'), ('unit', ''), ('value', 2.0), ('description', 'CWLS LOG ASCII STANDARD - VERSION 2.0')]), OrderedDict([('mnemonic', 'WRAP'), ('unit', ''), ('value', 'NO'), ('description', 'One line per depth step')]), OrderedDict([('mnemonic', 'PROD'), ('unit', ''), ('value', ''), ('description', 'LAS Producer')]), OrderedDict([('mnemonic', 'PROG'), ('unit', ''), ('value', 'LASO 4.1'), ('description', 'LAS Program name and version')])]

我需要将它写入一个csv文件中的一列,而不是多行。 头应该像mnemonic1,unit1,value1,description1,mnemonic2,unit2,value2,description2,…


Tags: nologvalueversionasciiunitdescriptionone
1条回答
网友
1楼 · 发布于 2024-05-23 17:42:56

我想你可以用这样的方法:

import collections
z = [collections.OrderedDict([('mnemonic', 'VERS'), ('unit', ''), ('value', 2.0), ('description', 'CWLS LOG ASCII STANDARD - VERSION 2.0')]), collections.OrderedDict([('mnemonic', 'WRAP'), ('unit', ''), ('value', 'NO'), ('description', 'One line per depth step')]), collections.OrderedDict([('mnemonic', 'PROD'), ('unit', ''), ('value', ''), ('description', 'LAS Producer')]), collections.OrderedDict([('mnemonic', 'PROG'), ('unit', ''), ('value', 'LASO 4.1'), ('description', 'LAS Program name and version')])]

final = ""
for k in z:
    final += "{},{},{},{},".format(k['mnemonic'], k['unit'], k['value'], k['description'])

with open('output.csv', 'w') as file:
    file.write(final.rstrip(","))

# VERS,,2.0,CWLS LOG ASCII STANDARD - VERSION 2.0,WRAP,,NO,One line per depth step,PROD,,,LAS Producer,PROG,,LASO 4.1,LAS Program name and version

您基本上需要通过OrderedDict项进行迭代,访问键(即:k['mnemonic'])并将结果写入文件

相关问题 更多 >