简体   繁体   English

python OrderedDict两个键和多个值->写入csv以导入到excel

[英]python OrderedDict two keys and multiple values -> write to csv to import into excel

In Python how do I write below object to a csv file which I can later manually import into Excel? 在Python中,我该如何将下面的对象写入一个csv文件,以后可以手动将其导入Excel?

from collections import OrderedDict
import csv

data = OrderedDict([(('2016-11-01', 'USD'), ['ECB News', 'FED News']),
                    (('2016-11-02', 'EUR'), ['Brexit News']),
                    (('2016-11-03', 'USD'), ['Yellen Speaking'])])

with open('output.csv', 'wb') as output:
    writer = csv.writer(output)
    for each in data:
        for key, value in each.iteritems(): #<<<<<----- error here
            writer.writerow([key, value])

Error: 错误:

  for key, value in each.iteritems():
    AttributeError: 'tuple' object has no attribute 'iteritems'

CSV output wanted: 想要的CSV输出:

2016-11-01;USD;ECB News,FED News
2016-11-02;EUR;Brexit News
2016-11-03;USD;Yellen Speaking

each is the key in the data dictionary, which it correctly says is a tuple. eachdata字典中的键,它正确地表示是一个元组。 You've probably just got the iteritems() in the wrong place: 您可能只是将iteritems()放在错误的位置:

from io import StringIO
with StringIO() as output:
    writer = csv.writer(output, delimiter=';')
    for k, v in data.iteritems():
        writer.writerow(list(k)+[','.join(v)])
    print(output.getvalue())

Output: 输出:

2016-11-01;USD;ECB News,FED News
2016-11-02;EUR;Brexit News
2016-11-03;USD;Yellen Speaking

You could replace: 您可以替换:

    for k, v in data.iteritems():
        writer.writerow(list(k)+[','.join(v)])

with: 与:

    writer.writerows(list(k)+[','.join(v)] for k, v in data.iteritems())

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

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