Reputation: 1135
data = [{'info': ('orange', 400000, 'apple'), 'photo': None}, {'info': ('grape', 485000, 'watermelon'), 'photo': None}]
I want to sort data
by the 2nd element (400000, 485000) in the tuple in the dictionary. How do I do this?
I followed another answer and my closest attempt was data.sort(key=lambda tup: tup[1])
, but that produces this error:
KeyError: 1
Upvotes: 1
Views: 61
Reputation: 402513
Use the inplace list.sort
method with a key
that indexes info
first, and then the data in the tuple:
data.sort(key=lambda x: x['info'][1])
Or, the not in-place sorted
function:
data = sorted(data, key=lambda x: x['info'][1])
Between the two, list.sort
is faster, because it sorts the data in-place, whereas sorted
has to create and return a copy of the data in data
.
A couple of other things you should think about;
info
as a key?info
tuple isn't even numeric?Do you want sort
to error out when it hits invalid data? Or would you rather introduce some means of handling these on a case-by-case basis? The key
would need to change accordingly.
Upvotes: 4
Reputation: 2084
For each dict item in the list you want to sort, you want to take the item's value keyed by 'info', which is a list, and sort on the second item (addressed as [1], counting from zero.
So: data.sort(key=lambda item: item['info'][1])
Upvotes: 0
Reputation: 71451
You can sort via key
:
data = [{'info': ('orange', 400000, 'apple'), 'photo': None}, {'info': ('grape', 485000, 'watermelon'), 'photo': None}]
new_data = sorted(data, key=lambda x:x.get('info', [0, 0])[1])
Upvotes: 0