【问题标题】:How to sort dict list with multiple key attributes - python如何对具有多个关键属性的字典列表进行排序 - python
【发布时间】:2015-07-01 23:32:19
【问题描述】:

我正在尝试根据两个关键参数对列表字典进行排序——“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()

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

【问题讨论】:

  • 我不确定我是否理解您想要的行为。你如何比较两个带有任意“id”和“type”字段的dicts?是否要先按其中一个字段排序,如果相同,再按第二个字段排序?
  • sorted(...,key=(type,id),reverse=True) 是他在他的例子中展示的

标签: python django list dictionary


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-16
    • 2021-08-10
    • 1970-01-01
    • 2019-02-08
    • 2021-12-10
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多