2009-08-15 90 views
2

在Python中使用CSV模塊時,我正在嘗試使用DictWriter類將字典轉換爲csv中的行。有沒有辦法處理嵌套字典?具體來說,我出口有一個結構類似這樣Disqus評論:DictWriter如何處理嵌套字典?

{ 
u'status': u'approved', 
u'forum': {u'id': u'', u'': u'', u'shortname': u'', u'name': u'', u'description': u''}, 
u'thread': {u'allow_comments': True, u'forum': u'', u'title': u'', u'url': u'', u'created_at': u'', u'id': u'', u'hidden': False, u'identifier': [], u'slug': u''}, 
u'is_anonymous': False, 
u'author': {u'username': u'', u'email_hash': u'', u'display_name': u'', u'has_avatar': True, u'url': u'', u'id': 1, u'avatar': {u'small': u'', u'large': u'', u'medium': u''}, u'email': u''}, 
u'created_at': u'2009-08-12T10:14', 
u'points': 0, 
u'message': u"", 
u'has_been_moderated': False, 
u'ip_address': u'', 
u'id': u'', 
u'parent_post': None 
} 

我想指定從作者和線程屬性的字段,並沒有找到一種方法爲止。下面的代碼:

f = open('export.csv', 'wb') 
fieldnames = ('id','status','is_anonymous','created_at','ip_address','points','has_been_moderated','parent_post','thread') 
try: 
    exportWriter = csv.DictWriter(f, 
     fieldnames, 
     restval=None, 
     extrasaction='ignore', 
     quoting=csv.QUOTE_NONNUMERIC 
     ) 

    for c in comments: 
     exportWriter.writerow(c) 

finally: 
    f.close() 

回答

1

我認爲你將不得不的主要問題是如何在CSV數據的一個平一行代表一個嵌套的數據結構。

你可以使用某種形式的名字mangeling來將從子字典的鍵變成頂級字典。

如線程 ':{u'allow_comments':

將成爲thread_allows_comments。

+0

我想挑出幾個,不一定完全轉換子字典,所以我希望只有一種方法來解決子字典屬性。但是,你是對的,可能必須先預處理和壓扁字典。 – RyanW 2009-08-15 23:00:29