如何使用多个键属性对字典列表进行排序 - python

时间:2015-07-01 23:32:20

标签: python django list dictionary

我正在尝试根据两个关键参数对列表字典进行排序 - " id"和"键入"。想象一下,你有一个如下所示的列表

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()

如何根据两个关键参数生成唯一列表?

1 个答案:

答案 0 :(得分:1)

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)