3

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

KingFish
  • 8,773
  • 12
  • 53
  • 81
  • And [Sort dict by sub-value in Python](http://stackoverflow.com/questions/18384570/sort-dict-by-sub-value-in-python?rq=1), and various other dups. Although most of them are about sorting a `dict`'s items rather than sorting a `list`, basically the same answer applies without the `.items()` part. – abarnert Jan 08 '14 at 18:50

2 Answers2

4
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 dicts, 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.)

abarnert
  • 354,177
  • 51
  • 601
  • 671
3

If you prefer to use lambda expressions, this is also an suitable way of solving your problem:

sorted(data, key=lambda x: x['key'])

So:

from pprint import pprint

data = [
    { 'some': 'thing9',
      'key': 9,
    },
    { 'some': 'thing3',
      'key': 3,
    },
    { 'some': 'thing2',
      'key': 2,
    },
    { 'some': 'thing1',
      'key': 1,
    }
]

pprint(sorted(data, key=lambda x:x['key']))

outputs

[{'key': 1, 'some': 'thing1'},
 {'key': 2, 'some': 'thing2'},
 {'key': 3, 'some': 'thing3'},
 {'key': 9, 'some': 'thing9'}]
Steinar Lima
  • 7,644
  • 2
  • 39
  • 40