Having (MVCE) list data
like below, I would like to sort it first by x coordinate, and later by y coordinate.
I have tried:
import operator
data = [
{ "coords": [142, -42]},
{ "coords": [147, -42]},
{ "coords": [151, -41]},
{ "coords": [147, -41]},
{ "coords": [149, -44]},
{ "coords": [150, -41]},
{ "coords": [149, -40]},
{ "coords": [150, -42]},
{ "coords": [151, -40]}
]
k1 = operator.itemgetter("coords")
# i've also tried various combinations like
#k2 = lambda data: operator.itemgetter(data["coords"][0]),\
# operator.itemgetter(data["coords"][1])
# but TypeError: list indices must be integers, not str
e = []
for d in sorted(data, key=k1):
e.append(d)
print("\n".join([str(s) for s in e]))
but this gives data being only sorted by X, but not Y next.
>>> { "coords": [142, -42]}
{ "coords": [147, -42]}
{ "coords": [147, -41]}
{ "coords": [149, -44]}
{ "coords": [149, -40]}
{ "coords": [150, -42]}
{ "coords": [150, -41]}
{ "coords": [151, -41]}
{ "coords": [151, -40]}
I'm aware that I can pass more than one argument to itemgetter. Is there a way to sort this in one statement?
(Desired result)
>>> { "coords": [142, -42]}
{ "coords": [147, -41]}
{ "coords": [147, -42]}
{ "coords": [149, -40]}
{ "coords": [149, -44]}
{ "coords": [150, -41]}
{ "coords": [150, -42]}
{ "coords": [151, -40]}
{ "coords": [151, -41]}
Data has to be added to e
list, as this is part of larger processing.
Not a duplicate of sort-list-of-dictionaries-by-another-list or similar that I managed to found here. Most people want to sort list of dictionaries by two values from dict, and here I want to sort by two values from nested list.