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?
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?
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}]