Home > Enterprise >  How can I write YAML from dictionary containing munch without "!munch.Munch"?
How can I write YAML from dictionary containing munch without "!munch.Munch"?

Time:03-17

When writing a yaml file from a dictionary containing munch.Munch one gets "!munch.Munch" as part of the output. How can I avoid this behavior?

Minimal example to show the problem

data = {"A":"a", "B":munch.Munch({"C":"c"})}
with open("test.yaml", "w") as file:
    yaml.dump(data, file)

Produces:

A: a
B: !munch.Munch
  C: c

But wanted output is:

A: a
B:
  C: c

Unfeasible solutions

Of course one could simply walk through the dictionary recursively and convert every munch.Munch into a dictionary, but I believe that there is a better solution than that. Writing munch.Munch directly to a yaml file works as intended and the difference between munch.Munch and dict is so tiny - there must be a better way. Any ideas?

CodePudding user response:

If munch.Munch is coming from this munch repository, you can use safe_dump instead of dump (from the readme).

data = {"A":"a", "B":munch.Munch({"C":"c"})}
with open("test.yaml", "w") as file:
    yaml.safe_dump(data, file)

It produces what you want:

A: a
B:
  C: c

  • Related