简体   繁体   中英

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?

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:

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. You've probably just got the iteritems() in the wrong place:

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())

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