简体   繁体   English

将包含字符串和字典的列表写入 csv 文件

[英]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?我有一个列表,列表的第一个元素中有字符串,第二个元素中有一个字典,其中有一些标志和相关的计数,我如何将它写入 python 中的 csv 文件?

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]其中 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.我正在猜测您的数据是什么样的,但我认为您可以将列表中的两个项目组合成一个 dict,然后只使用DictWriter来编写整个内容。 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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