简体   繁体   中英

write a list of ordered dictionaries to a csv file in 1 single column in python

I have OrderedDict like

[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')])]

I need to write it to a csv file in a single column rather than multiple rows. The header should look like mnemonic1,unit1,value1,description1,mnemonic2,unit2,value2,description2,…

I guess you can use something like:

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

You basically need to iterate trough the OrderedDict items, access the keys (ie: k['mnemonic'] ) and write the results to a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM