Python 使用defaultdict时需要忽略yaml输出中的值

Python 使用defaultdict时需要忽略yaml输出中的值,python,dictionary,yaml,Python,Dictionary,Yaml,以下代码段: 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/n

以下代码段:

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