[英]Python - Sort a list by a certain element in a tuple in a dictionary
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. 我想按字典中元组中的第二个元素(400000,485000)对
data
进行排序。 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: 我遵循了另一个答案,最接近的尝试是
data.sort(key=lambda tup: tup[1])
,但这会产生此错误:
KeyError: 1
KeyError:1
Use the inplace list.sort
method with a key
that indexes info
first , and then the data in the tuple: 将
list.sort
方法与首先对info
索引, 然后对元组中的数据索引的key
一起使用:
data.sort(key=lambda x: x['info'][1])
Or, the not in-place sorted
function: 或者, 不是就地
sorted
函数:
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
. 在这两者之间,
list.sort
更快,因为它可以对数据进行就地sorted
,而sorted
必须创建并返回data中的data
副本。
A couple of other things you should think about; 您应该考虑的其他几件事;
info
as a key? info
作为密钥怎么办? info
tuple isn't even numeric? info
元组中的第二个元素甚至不是数字怎么办? Do you want sort
to error out when it hits invalid data? 您是否希望
sort
在遇到无效数据时出错? Or would you rather introduce some means of handling these on a case-by-case basis? 还是您宁愿介绍一些根据具体情况进行处理的方法? The
key
would need to change accordingly. key
将需要相应地更改。
You can sort via key
: 您可以通过
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. 对于要排序的列表中的每个dict项,您都希望采用以'info'键为列表的项的值,然后对第二个项(地址为[1],从零开始计数)进行排序。
So: data.sort(key=lambda item: item['info'][1])
因此:
data.sort(key=lambda item: item['info'][1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.