1

I am trying to construct a yaml document by using a recursive function returning defaultdict on arbitrary levels from this stackoverflow recipe. Python 3.8.2

from collections import defaultdict
import yaml

def ret_dd():
    return defaultdict(ret_dd)

yml = ret_dd()
yml['a']['b']['c'] = 1
with open('newfile.txt','w') as f:
    yaml.dump(yml, f)

The outcome of the file I'm writing to I would like to see:

a:
 b:
  c: 1 

however, what I'm seeing is:

!!python/object/apply:collections.defaultdict
args:
- &id001 !!python/name:__main__.ret_dd ''
dictitems:
  a: !!python/object/apply:collections.defaultdict
    args:
    - *id001
    dictitems:
      b: !!python/object/apply:collections.defaultdict
        args:
        - *id001
        dictitems:
          c: !!python/object/apply:collections.defaultdict
            args:
            - *id001

What step am I missing?

Jacksgrin
  • 85
  • 1
  • 11
  • You could use [this](https://stackoverflow.com/questions/26496831/how-to-convert-defaultdict-of-defaultdicts-of-defaultdicts-to-dict-of-dicts-o) or [this](https://stackoverflow.com/a/32303615/6243352) to convert to a normal dict, then run your yaml dumper. – ggorlen May 20 '20 at 21:46

0 Answers0