[Tutor] Sorting and secondary sorting.
Karl Pflästerer
khp at pflaesterer.de
Sat Mar 11 15:53:27 CET 2006
On 11 Mrz 2006, ml.cyresse at gmail.com wrote:
> 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"},
> ]
>
> So, I'm trying to sort and then do a secondary sort. I'd like to do it
> Pythonically; currently I'm creating a Pysqlite db in memory and
> sticking the data in a table, and selecting it back out with an ORDER
> BY clause, and then reconstituting it into dictionaries in a list.
One easy way could be:
.>>> l = [ { "host":"foo", "db":"bob"},
. { "host":"foo", "db":"dave"},
. { "host":"fee", "db":"henry"}
. ]
.... ... ... >>> l.sort(key=lambda d: (d['host'], d['db']))
.>>> l
.[{'host': 'fee', 'db': 'henry'}, {'host': 'foo', 'db': 'bob'}, {'host': 'foo', 'db': 'dave'}]
Or you write the above explicitly with DSU; decorate with a tuple of
host name and db name, sort and undecorate.
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list