简体   繁体   中英

Write a list having string and dictionary to a csv file

I have a list having string in the first element of a list and a dictionary in the second element which has some flags and associated counts with it, how can i write it to a csv file in python?

list is as follows

['(RenderThread)', 
  Counter({'flags=4': 752, 'flags=40': 299, 'flags=10004': 283,
           'flags=80': 203, 'flags=90002': 36, 'flags=10080': 31, 
           'flags=100': 23, 'flags=10040': 14, 'flags=10100': 9})]
<type 'list'>

I want output as follows

RenderThread    flags=100   flags=10004 flags=10040 flags=10080 flags=10100 flags=4 flags=40    flags=80    flags=90002
                      23            283          14          31           9     752      299        203             36

here is my code snippet

with open(outputcsv,'wb') as outcsv:
    writer = csv.writer(outcsv,delimiter=',')
    for x in threads:
        writer.writerows([x.split(',')])
        w = csv.DictWriter(outcsv,data1)
        w.writerow(counter1)
        writer.writerows('\n')

where data1 = [thr1,counter1]

I'm taking a guess about what your data looks like, but I think you can combine the two items in the list into a single dict and then just use DictWriter to write the whole thing. There are several oddities, including my guess about what your data list looks like and that you want comma separators even though you show a bunch of space padding in your output. Working examples can really help sort some of these questions out.

import csv

# example input
data = ['(RenderThread)', {'flags=4': 752, 'flags=40': 299}]

# presumably its one of many in an outer list
threads = [data]

def render_thread_iter(threads):
    """Given an interator that emits [RenderThread, FlagsDict] lists,
    iterate dicts where render thread is added to flags dict.
    """
    for data in threads:
        d = {'RenderThread':data[0]}
        d.update(data[1])
        yield d

with open('output.csv','w', newline='') as outcsv:
    # create list of header fields
    fieldnames = ['RenderThread'] + sorted(threads[0][1].keys())
    writer = csv.DictWriter(outcsv, delimiter=',', fieldnames=fieldnames)
    # write rendered dicts
    writer.writeheader()
    writer.writerows(render_thread_iter(threads))

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