Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to omit values from yaml output when using defaultdict

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!

like image 319
fr00z1 Avatar asked Oct 11 '13 15:10

fr00z1


1 Answers

You need to register a representer with the yaml module:

from yaml.representer import Representer
yaml.add_representer(collections.defaultdict, Representer.represent_dict)

Now yaml.dump() will treat defaultdict objects as though they were dict objects:

>>> print yaml.dump(data)
this:
  is: {me: test}

>>> print yaml.dump(data, default_flow_style=False)
this:
  is:
    me: test
like image 87
Zero Piraeus Avatar answered Oct 06 '22 16:10

Zero Piraeus