Sorting a dictionary field belonging to a list

Chris Green cmg at dok.org
Fri Sep 17 21:15:17 CEST 2004


Jocknerd <jocknerd1 at yahoo.com> writes:

> My question is how would I go about sorting the output based on team['pf']
> for instance?

The simplest way would be to use the sort method on the list in the
first place.  That method takes an optional comparison function that
you would have to write.  See help(lst.sort)

lst = [ {'name': 'z'}, {'name': 'd'}, {'name': 'e'} ]

def mycmp(a,b):
    return cmp(a['name'],b['name'])

lst.sort(mycmp)

If the original order is important to you, you will be to use
something like copy.copy() to make a copy of the list.  


-- 
Chris Green <cmg at dok.org>
"Yeah, but you're taking the universe out of context."



More information about the Python-list mailing list