django - How to sort dict list with multiple key attributes - python -


i trying sort list dict based on 2 key parameters - "id" , "type". imagine have list 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 this.

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

i tried method produces unique list based on "key" attribute.

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

how can generate unique list based on 2 key parameters?

seen_items = set() filtered_dictlist = (x x in dict_list                       if (x["id"], x["type"]) not in seen_items                       , 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 , sort how want ...

you can use itemgetter make more elegant

from operator import itemgetter my_getter = itemgetter("type", "id") seen_items = set() filtered_values = [x x in dict_list                     if my_getter(x) not in seen_items                     , not seen_items.add(my_getter(x))] sorted_list = sorted(filtered_dictlist, key=my_getter, reverse=true) 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -