Write Nested Dictionary to CSV

て烟熏妆下的殇ゞ 提交于 2021-01-27 18:45:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!