以下代码段:
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"
任何帮助表示赞赏!
答案 0 :(得分:5)
您需要使用yaml
模块注册一个代表:
from yaml.representer import Representer
yaml.add_representer(collections.defaultdict, Representer.represent_dict)
现在yaml.dump()
会将defaultdict
个对象视为dict
个对象:
>>> print yaml.dump(data)
this:
is: {me: test}
>>> print yaml.dump(data, default_flow_style=False)
this:
is:
me: test