在python中的1个单列中将有序词典列表写入csv文件

时间:2018-09-03 19:14:31

标签: python csv

我有OrderedDict之类的

[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,…

1 个答案:

答案 0 :(得分:0)

我猜你可以使用类似的东西:

quantity

您基本上需要遍历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)并将结果写入文件。