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

时间:2016-11-18 23:59:34

标签: python csv dictionary

在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])

错误:

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

需要CSV输出:

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

1 个答案:

答案 0 :(得分:1)

eachdata字典中的关键字,它正确地说是一个元组。你可能只是把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())

输出:

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

您可以替换:

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

使用:

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