以下代码片段:
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"
感谢任何帮助!
最佳答案
您需要向 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
关于python - 使用 defaultdict 时需要从 yaml 输出中省略值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19321776/