1

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?

Cornelius Roemer
  • 3,772
  • 1
  • 24
  • 55
  • 1
    If speed is not an issue, I'd personally just recursively convert any ordered dicts to dicts. Also note that in Python 3 the dicts are ordered anyway, so you may not even need to do it this way. – Peter Jun 30 '21 at 13:52
  • Does this answer your question? [How to use OrderedDict as an input in yaml.dump or yaml.safe\_dump?](https://stackoverflow.com/questions/42518067/how-to-use-ordereddict-as-an-input-in-yaml-dump-or-yaml-safe-dump) – Yevhen Kuzmovych Jun 30 '21 at 13:53
  • @Peter *[Python 3.7](/q/39980323/4518341) – wjandrea Jun 30 '21 at 15:25
  • I mean, is there some problem with iterating over your list and converting to dict? It seems trivial. – juanpa.arrivillaga Jun 30 '21 at 17:43
  • @juanpa.arrivillaga it's a big dict of dicts and lists, nested many levels deep. Can iterate over it but it needs a custom function, unless you know of a module? – Cornelius Roemer Jun 30 '21 at 19:17

1 Answers1

2

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
Cornelius Roemer
  • 3,772
  • 1
  • 24
  • 55