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?
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))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With