machin machin - 2 months ago 36
YAML Question

Check that data in YAML file are in alphabetical order in python

I need to check (verify) in python that data in YAML file are in alphabetical order by some field (see example below).
Let's suppose I have some file with data in YAML format:

project: presentations/demo1
description: Some description for demo1 project
owner: John Doe

project: templates/template_demo
description: Some template_demo
owner: Sarah Connor

So, I have to be sure that data in this file are sorted by 'project' name.
Actually, I have some solutions that is based on getting all projects names (from respective list of dicts), sort them and, then, compare with raw YAML file. But maybe there are more better solutions.


If you simplify this problem a bit, it becomes

Check if a list is in sorted order

You can refer to nice ways to do it here

l = [ 4, 2, 3, 7, 8 ]
# this does not have to be sorted, you just have to check that the
# current entry is less than the next one
all(l[i] <= l[i+1] for i in xrange(len(l)-1))

In your case it becomes

data = parse_yaml_file() # parse your yaml data
is_sorted = all(data[i]['project'] <= data[i+1]['project'] for i in xrange(len(data)-1))