[Tutor] Sorting and secondary sorting.

Liam Clarke ml.cyresse at gmail.com
Sun Mar 12 03:05:25 CET 2006


Ahaha, thanks guys, I knew I was overlooking something.

Regards,

Liam Clarke

On 3/12/06, Kent Johnson <kent37 at tds.net> wrote:
> 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