K S K S - 18 days ago 7
Python Question

python OrderedDict two keys and multiple values -> write to cvs to import into excel

In Python how do I write below object to cvs 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'


CVS output wanted:

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

Answer

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