![](/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.