Python: Sorting an array based on a subvalue

python, python-2.7

Solution

sorted(data, key=operator.itemgetter('key'))

The Sorting HOWTO explains this in more detail. But the basic idea is that all sort-related functions take a `key` argument, a callable that's applied to each value before comparing the values.

So, we want `key` to take one of the elements of your `list`, and return the thing you want to sort by. The elements are `dict`s, and you want to sort by their `key` item. The `itemgetter` function does exactly what you want. (If that function weren't available, you could use, e.g., `lambda item: item['key']` instead.)

Problem

I have the following data structure: ``` [ { some: thing9, key: 9, }, { some: thing3, key: 3, }, { some: thing2, key: 2, }, { some: thing1, key: 1, } ] ``` How can I sort this array based on the key value of the dictionary so I get: ``` [ { some: thing1, key: 1, }, { some: thing2, key: 2, }, { some: thing3, key: 3, }, { some: thing9, key: 9, } ] ``` Thanks

Original source

Related problems