![](/img/trans.png)
[英]how to sort list of dict by dict[key][key] in one line(Python3)
[英]How to sort dict list with multiple key attributes - python
我正在尝试基于两个关键参数-“ id”和“ type”对列表字典进行排序。 假设您有一个类似以下的列表
dict_list = [
{ "id" : 1, "type" : "snippet", "attribute" :'test'},
{ "id" : 2, "type" : "snippet", "attribute" :'hello'},
{ "id" : 1, "type" : "code", "attribute" : 'wow'},
{ "id" : 2, "type" : "snippet", "attribute" :'hello'},
]
最终结果应该是这样的。
dict_list = [
{ "id" : 1, "type" : "snippet", "attribute" : 'test' },
{ "id" : 2, "type" : "snippet", "attribute" : 'hello' },
{ "id" : 1, "type" : "code", "attribute" : 'wow' },
]
我尝试了这种方法,但它仅基于“ key”属性仅生成一个唯一列表。
unique_list = {v['id'] and v['type']:v for v in dict_list}.values()
如何基于两个关键参数生成唯一列表?
seen_items = set()
filtered_dictlist = (x for x in dict_list
if (x["id"], x["type"]) not in seen_items
and not seen_items.add((x["id"], x["type"])))
sorted_list = sorted(filtered_dictlist,
key=lambda x: (x["type"], x["id"]),
reverse=True)
我认为应该先过滤,然后按需要对其进行排序...
您可以使用itemgetter使它更优雅
from operator import itemgetter
my_getter = itemgetter("type", "id")
seen_items = set()
filtered_values = [x for x in dict_list
if my_getter(x) not in seen_items
and not seen_items.add(my_getter(x))]
sorted_list = sorted(filtered_dictlist, key=my_getter, reverse=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.