import yaml

def represent_dict(self, data):
    def key_function((key,value)):
        # Prioritizes certain keys when sorting.
        prio = {"model":0,"pk":1,"fields":2}.get(key,99)
        return (prio, key)
    items = data.items()
    return self.represent_mapping(u'tag:yaml.org,2002:map', items)


Sam Kuper skrev:
Dear list,

Bearing in mind I'm new to PyYAML, please could you help with the following.

I'm using PyYAML to convert dumped YAML data from Django (which is flow style by default) into block style via the following Python script:


This works, but I'd like to output the data in the order shown here - in other words, in the form:

- model:

I'd also like the fields to be sorted alphabetically.

This ticket suggests to me that this should be possible, but I'm not sure how best to insert a "custom representer" into the script above, in order to get the result I'm seeking.

I'd be grateful for any help you can offer.

Many thanks in advance,