python - Ruamel yaml formatting of dumped nested lists -
i dump dictionary components nested lists, each row of list on own line. want maintain dictionary order.
here's mwe:
import sys ruamel import yaml ruamel.yaml import yaml d = {'b':1, 'a':[[1, 2],[3, 4]]} # desired output: # b: 1 # a: # - [1, 2] # - [3, 4] print() yaml.dump(d, sys.stdout) print('\n') yaml().dump(d, sys.stdout)
and here's get:
a: - [1, 2] - [3, 4] b: 1 b: 1 a: - - 1 - 2 - - 3 - 4
the first method has nested-list formatting want, loses dictionary order. (not surprise since i'm not using round-trip dumper) second method manages maintain order, loses desired nested list formatting. time use round-trip dumper, i've lost nice nested list formatting.
any tips here?
that dictionary has order want either luck, or because using python 3.6. in older versions of python (i.e < 3.6) order not guaranteed.
if targeting 3.6 , have ruamel.yaml>=0.15.32
can do:
import sys ruamel import yaml ruamel.yaml import yaml d = {'b':1, 'a':[[1, 2],[3, 4]]} y = yaml() y.default_flow_style = none y.dump(d, sys.stdout)
if have older version , python 3.6:
import sys ruamel import yaml ruamel.yaml import yaml y = yaml() d = {'b':1, 'a':[y.seq([1, 2]),y.seq([3, 4])]} seq in d['a']: seq.fa.set_flow_style() y.dump(d, sys.stdout)
to get:
b: 1 a: - [1, 2] - [3, 4]
to order want in older versions of python consistently should do:
d = y.map() d['b'] = 1 d['a'] = y.seq([1, 2]),y.seq([3, 4])
and ruamel.yaml>=0.15.32
can leave out call y.seq()
.
Comments
Post a Comment