masanorinyo
masanorinyo

Reputation: 1128

How to sort dict list with multiple key attributes - python

I am trying to sort list dict based on two key parameters - "id" and "type". Imagine you have a list like the below

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'},
 ]

The end result should be like this.

dict_list = [
    { "id" : 1, "type" : "snippet", "attribute" : 'test' },
    { "id" : 2, "type" : "snippet", "attribute" : 'hello' },
    { "id" : 1, "type" : "code", "attribute" : 'wow' },
]

I tried this method but it only produces a unique list based on only "key" attribute.

unique_list = {v['id'] and v['type']:v  for v in dict_list}.values()

How can I generate a unique list based on two key parameters?

Upvotes: 1

Views: 154

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113930

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)

I think should first filter and then sort it how you want ...

you can use itemgetter to make it more elegant

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)

Upvotes: 1

Related Questions