问题
I am trying to write a nested dictionary to CSV in Python. I looked at the csv.DictWriter documentation on python.org and some of the examples here on stackoverflow but I can't figure out the last part. Here is a representative data set:
data = {u'feeds': [{u'feed_code': u'free', u'feed_name': u'Free'}, {u'feed_code': u'paid', u'feed_name': u'Paid'}, {u'feed_code': u'grossing', u'feed_name': u'Grossing'}], u'code': 200}
ColTitle = ['code','feed_code','feed_name']
with open('test.csv','wb') as f:
w = csv.DictWriter(f, ColTitle)
w.writeheader()
for item in data:
w.writerow({field: data[item]}) ## Part I am stuck on
This is what I would like to write to my CSV file
code feed_code feed_name
200 free Free
200 paid Paid
200 grossing Grossing
回答1:
The problem in your code is the loop. You want to loop over all the feeds, but you were actually looping over the data. Your for:
for item in data:
print item
w.writerow({field: data[item]}) ## Part I am stuck on
This would give you
feeds
code
What you want is to loop over the feeds, like so:
for feed in data[u'feeds']:
w.writerow(feed)
Yet this isn't enough, because the code isn't in every field, but only declared once in the data, so you should change it to also include the code in every row written:
for feed in data[u'feeds']:
w.writerow(dict(feed, code=data[u'code']))
回答2:
This tricky part about what you want to do is that the dictionaries in the list of u'feeds'
in your data structure do not have the u'code'
value in each of them. This can be easily remedied by updating each of them which will allow you to write all of them out at one time (although it does change the data structure):
import csv
data = {u'code': 200,
u'feeds': [{u'feed_code': u'free', u'feed_name': u'Free'},
{u'feed_code': u'paid', u'feed_name': u'Paid'},
{u'feed_code': u'grossing', u'feed_name': u'Grossing'}]}
COL_TITLES = ['code', 'feed_code', 'feed_name']
with open('test.csv', 'wb') as f:
w = csv.DictWriter(f, COL_TITLES, delimiter=' ')
w.writeheader()
code = data['code']
for feed in data['feeds']:
feed.update(code=code)
w.writerows(data['feeds'])
来源:https://stackoverflow.com/questions/38798987/write-nested-dictionary-to-csv