fr0*_*0z1 4 python dictionary yaml
以下代码段:
import yaml
import collections
def hasher():
return collections.defaultdict(hasher)
data = hasher()
data['this']['is']['me'] = 'test'
print yaml.dump(data)
Run Code Online (Sandbox Code Playgroud)
返回:
!!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}
Run Code Online (Sandbox Code Playgroud)
我该如何删除:
!!python/object/apply:collections.defaultdict
[*id001]
Run Code Online (Sandbox Code Playgroud)
最终目标是:
this:
is:
me: "test"
Run Code Online (Sandbox Code Playgroud)
任何帮助赞赏!
您需要在yaml模块中注册一个代表:
from yaml.representer import Representer
yaml.add_representer(collections.defaultdict, Representer.represent_dict)
Run Code Online (Sandbox Code Playgroud)
现在yaml.dump()将defaultdict对象视为dict对象:
>>> print yaml.dump(data)
this:
is: {me: test}
>>> print yaml.dump(data, default_flow_style=False)
this:
is:
me: test
Run Code Online (Sandbox Code Playgroud)