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
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.
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])
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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.