Sorting two dimentional array by column?
Tobiah
toby at tobiah.org
Wed Jul 2 18:22:34 EDT 2008
>> 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.
Sorry to reply to myself so many times, but I have come
up with the answer:
from operator import itemgetter
thing = [
{'animal': 'duck', 'tool': 'pond'},
{'animal': 'dog', 'tool': 'bone'},
{'animal': 'bear', 'tool': 'hive'}
]
get = itemgetter('animal')
thing.sort(key = get)
print thing
*****************************************
[
{'tool': 'hive', 'animal': 'bear'},
{'tool': 'bone', 'animal': 'dog'},
{'tool': 'pond', 'animal': 'duck'}
]
** Posted from http://www.teranews.com **
More information about the Python-list
mailing list