Re: Custom sort order for YAML output
Markus Jarderot <[email protected]>
| Newsgroups | gmane.text.yaml.general |
|---|---|
| Message-ID | <[email protected]> |
[BEGIN]
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()
items.sort(key=key_function)
return self.represent_mapping(u'tag:yaml.org,2002:map', items)
yaml.add_representer(represent_dict)
[END]
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:
>
> [BEGIN]...[END]
>
> This works, but I'd like to output the data in the order shown here
> <http://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-data-with-fixtures>
> - in other words, in the form:
>
> - model:
> pk:
> fields:
>
> I'd also like the fields to be sorted alphabetically.
>
> This ticket <http://pyyaml.org/ticket/23> 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,
>
> Sam
------------------------------------------------------------------------------
Come build with us! The BlackBerry® Developer Conference in SF, CA
is the only developer event you need to attend this year. Jumpstart your
developing skills, take BlackBerry mobile applications to market and stay
ahead of the curve. Join us from November 9-12, 2009. Register now!
http://p.sf.net/sfu/devconf
_______________________________________________
Yaml-core mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/yaml-core