1

Suppose I have a coordinate list as the following:

list_ = [{'x':1,'y':2},{'x':1,'y':1},{'x':3,'y':3}]

I want to first sort x key, and then sort y key. So I expect:

list_ = [{'x':1,'y':1},{'x':1,'y':2},{'x':3:'y':3}]

How do I do?

Burger King
  • 2,945
  • 3
  • 20
  • 45

1 Answers1

3

Use the key parameter of sort/sorted. You pass a function that returns the key to sort upon. operator.itemgetter is an efficient way to generate the function:

>>> from operator import itemgetter
>>> list_ = [{'x':1,'y':2},{'x':1,'y':1},{'x':3,'y':3}]
>>> sorted(list_,key=itemgetter('x','y'))
[{'x': 1, 'y': 1}, {'x': 1, 'y': 2}, {'x': 3, 'y': 3}]
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251