6

Following code snippet:

import yaml
import collections

def hasher():
  return collections.defaultdict(hasher)

data = hasher()

data['this']['is']['me'] = 'test'

print yaml.dump(data)

This returns:

!!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}

How would I remove:

!!python/object/apply:collections.defaultdict
[*id001]

End goal is:

  this: 
    is: 
      me: "test"

Any help appreciated!

4

1 回答 1

15

您需要在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
于 2013-10-11T16:37:20.210 回答