[Tutor] Sorting and secondary sorting.
Kent Johnson
kent37 at tds.net
Sat Mar 11 16:13:05 CET 2006
Liam Clarke wrote:
> Hi all,
>
> I'm trying to think of a way to sort a list of dictionaries. In pseudo-code:
>
> l = [ { "host":"foo", "db":"bob"},
> { "host":"foo", "db":"dave"},
> { "host":"fee", "db":"henry"}
> ]
>
> l.sort( key = lambda item: item["host"], second_key = lambda item: item["db"])
>
> Which, if all went well, would give me -
>
> l = [ { "host":"fee", "db":"henry"}
> { "host":"foo", "db":"bob"},
> { "host":"foo", "db":"dave"},
> ]
>
Just make a key that includes both of the values you want to sort on as
a tuple:
l.sort( key = lambda item: (item["host"], item["db"]))
Kent
More information about the Tutor
mailing list