【发布时间】: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