Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use OrderedDict as an input in yaml.dump or yaml.safe_dump?

Tags:

python

yaml

my question is very simple. I have a OrderredDict object with customized order, I want to convert it to yaml format. But it seems yaml.dump couldn't take Orderredict as an Input. Anyone know how to do it?

like image 324
yabchexu Avatar asked Feb 28 '17 20:02

yabchexu


2 Answers

It looks like you want this solution, which adds a "representer" to YAML.

Assuming you have an object my_object that consists of nested lists, dicts, and/or OrderedDicts ... you can dump this to YAML if you add these lines:

yaml.add_representer(OrderedDict, lambda dumper, data: dumper.represent_mapping('tag:yaml.org,2002:map', data.items()))
output = yaml.dump(my_object)

I also find it necessary to convert my tuples to lists:

yaml.add_representer(tuple, lambda dumper, data: dumper.represent_sequence('tag:yaml.org,2002:seq', data))
like image 123
Ethan T Avatar answered Oct 09 '22 22:10

Ethan T


This works only for dictionary, not OrderedDict, but you may be able to convert it without losing the order.

If you are using PyYaml 5.1 or later, you can dump a dictionary in its current order by simply using

yaml.dump(data, default_flow_style=False, sort_keys=False)
like image 31
Phil B Avatar answered Oct 09 '22 21:10

Phil B