Dims
Dims

Reputation: 51249

How to pretty print dict YAML-like in Python?

I have a dict with strings, lists, numbers and so on simple types. I can pretty print it with json.dumps, but yaml would be cleaner. Can I print dict with yaml tools?

If I do

import yaml

with open("out.yaml", 'w') as out:
    yaml.dump(mydic, out)

I get a lot of boilerplate like !!python/object/apply:collections.OrderedDict

Upvotes: 0

Views: 1100

Answers (1)

flyx
flyx

Reputation: 39788

You need to add a representer that presents the OrderedDict as a normal YAML mapping:

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

Or, if you are using Python 3.7+, just do away with OrderedDict and use dict since it retains insertion order from that version on. dict will presented without explicit tag by default.

Upvotes: 1

Related Questions