Sub-sort after sort

K

keeftm

Hello, I have been sorting a list of dicts using the following
function:

result_rs = sorted(unsort_rs, key=itemgetter(orderby))

and this works fine. Now I am looking to perform a subsort as well.
For example, I have this:

test = [{'name': 'John Smith', 'location': 'CA',},{'name': 'John
Smith', 'location': 'AZ',},]

I would want to sort by name first, then sub sort by location. Any
ideas? Thanks!
 
K

KeefTM

Hello, I have been sorting a list of dicts using the following
function:

result_rs = sorted(unsort_rs, key=itemgetter(orderby))

and this works fine. Now I am looking to perform a subsort as well.
For example, I have this:

test = [{'name': 'John Smith', 'location': 'CA',},{'name': 'John
Smith', 'location': 'AZ',},]

I would want to sort by name first, then sub sort by location. Any
ideas? Thanks!

Well, I found a way to do it. Just create a new key and value that is
a combination of two other values, like this:

test = [{'name': 'John Smith', 'location': 'AZ','sort':'John SmithAZ'},
{'name': 'John
Smith', 'location': 'CA', 'sort':'John SmithCA'},]

Not pretty in the slightest, but it works.
 
A

Andrew Koenig

I would want to sort by name first, then sub sort by location. Any
ideas? Thanks!

In Python 2.3 and later, sorting is stable -- so you can sort successively
in reverse order. In other words, sort the list by location, then sort the
sorted result again by name and you should get what you want.
 
K

KeefTM

In Python 2.3 and later, sorting is stable -- so you can sort successively
in reverse order. In other words, sort the list by location, then sort the
sorted result again by name and you should get what you want.

I'm using Python 2.4 and I thought that was the first thing I tried.
Let me verify. Thanks!
 
K

KeefTM

In Python 2.3 and later, sorting is stable -- so you can sort successively
in reverse order. In other words, sort the list by location, then sort the
sorted result again by name and you should get what you want.

That was it. I must of made a mistake when I tried it before. Thanks!
 
P

Paul Hankin

Hello, I have been sorting a list of dicts using the following
function:

result_rs = sorted(unsort_rs, key=itemgetter(orderby))

and this works fine. Now I am looking to perform a subsort as well.
For example, I have this:

test = [{'name': 'John Smith', 'location': 'CA',},{'name': 'John
Smith', 'location': 'AZ',},]

I would want to sort by name first, then sub sort by location. Any
ideas? Thanks!

test.sort(key=lambda x:(x['name'], x['location']))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top