2013-10-11 45 views
2

下面的代碼時,可以省略從YAML輸出值:需要使用defaultdict

import yaml 
import collections 

def hasher(): 
    return collections.defaultdict(hasher) 

data = hasher() 

data['this']['is']['me'] = 'test' 

print yaml.dump(data) 

這將返回:

!!python/object/apply:collections.defaultdict 
args: [&id001 !!python/name:__main__.hasher ''] 
dictitems: 
    this: !!python/object/apply:collections.defaultdict 
    args: [*id001] 
    dictitems: 
     is: !!python/object/apply:collections.defaultdict 
     args: [*id001] 
     dictitems: {me: test} 

我將如何去除:

!!python/object/apply:collections.defaultdict 
[*id001] 

的最終目標是:

this: 
    is: 
     me: "test" 

任何幫助表示讚賞!

回答

4

您需要用yaml模塊註冊一個申述:

from yaml.representer import Representer 
yaml.add_representer(collections.defaultdict, Representer.represent_dict) 

現在yaml.dump()將他們彷彿是dict對象對待defaultdict對象:

>>> print yaml.dump(data) 
this: 
    is: {me: test} 

>>> print yaml.dump(data, default_flow_style=False) 
this: 
    is: 
    me: test 
+0

謝謝你,這個工作精美。 – user2152283