Cornelius Roemer
Cornelius Roemer

Reputation: 8276

Make ordered dicts behave like normal dicts in yaml.dump output

When serializing an OrderedDict with yaml.dump() the output is quite difficult to comprehend due to the many dashes:

refine: !!python/object/apply:collections.OrderedDict
- - - root
    - Wuhan/Hu-1/2019
  - - clock_rate
    - 0.0007
  - - clock_std_dev
    - 0.0003

Is there a way to make yaml.dump() serialize OrderedDicts just like normal Dicts? What I want is the much more readable:

refine:
  root: Wuhan/Hu-1/2019
  clock_rate: 0.0007
  clock_std_dev: 0.0003

Do I need to iterate through the entire variable (it's composed of hundreds of dicts, the above is just an excerpt) and cast all OrderedDicts as Dicts or is there an in-built feature of yaml.dump() or a similar library that does this for me?

Upvotes: 1

Views: 207

Answers (1)

Cornelius Roemer
Cornelius Roemer

Reputation: 8276

Using ruamel.yaml as drop in replacement for PyYAML solved the problem instantly. OrderedDicts are no longer represented as lists in the output.

This code:

import ruamel.yaml

yaml=ruamel.yaml.YAML()
yaml.dump()

Produces the much neater output:

refine: !!omap
- root: Wuhan/Hu-1/2019
- clock_rate: 0.0007
- clock_std_dev: 0.0003

Upvotes: 2

Related Questions