Sorting two dimentional array by column?

John Machin sjmachin at lexicon.net
Wed Jul 2 18:29:28 EDT 2008


On Jul 3, 7:35 am, Tobiah <t... at tobiah.org> wrote:
> > Imagine an excel spreadsheet.  I can choose
> > a column and sort the records based on the items
> > in that column.  I would like to do the same
> > thing with a large two dimensional array.
> > What would be the fastest way (in computation time)
> > to accomplish this?
>
> Now that I think about the problem more, I really want
> to sort an array of dictionaries according one of the
> keys of each.  Could I use:
>
> array.sort(key = something)
>
> Where something looks at the proper item in the
> current row?  I can't quite visualize how to pull
> the item out of the dictionary.

Manual sez: """key specifies a function of one argument that is used
to extract a comparison key from each list element: "key=str.lower"
"""

Assuming that "sort an array of dictionaries according one of the keys
of each" means "sort an array of dictionaries according to the value
stored for one of the keys of each".

If the dict key were a constant, you could do:

array.sort(key=lambda adict: adict['the_constant_key'])

However you want the current row, and sort wants a 1-arg key
function  ... to stick with the key= caper you'll need to curry the
extra arg. So (Python 2.5 onwards):

# do this once
import functools
def dict_extract(adict, akey):
   return adict[akey]

# do this each time you want to sort
current_row_key = whatever()
sort_key_func = functools.partial(dict_extract, akey=current_row_key)
array.sort(key=sort_key_func)

Alternatively, use the decorate-sort-undecorate procedure:

temp = [(d[current_row_key], d) for d in array]
temp.sort()
array[:] = [tup[1] for tup in temp]

HTH,
John



More information about the Python-list mailing list