使用defaultdict时,需要省略yaml输出中的值

时间:2013-10-11 15:24:12

标签: 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/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"

任何帮助表示赞赏!

1 个答案:

答案 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