Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dict list with itemgetter

Tags:

python

Here is my dictionary:

a = [{"id":1,"data":{"age":16,"name":a}}, 
     {"id":3,"data":{"age":35,"name":b}}, 
     {"id":2,"data":{"age":9,"name":c}}]

I want to sort it by the field "age".

With lambda I use:

sorted(a, key=lambda k: k['data']['age'])

How to do this with itemgetter?

like image 584
user2863748 Avatar asked Oct 21 '22 23:10

user2863748


1 Answers

You'd better start by adding quotes to "a", "b" and "c", otherwise you will have a confusion between dict a and char "a"

a = [{"id":1,"data":{"age":16,"name":"a"}}, 
     {"id":3,"data":{"age":35,"name":"b"}}, 
     {"id":2,"data":{"age":9,"name":"c"}}]

For the itemgetter :

from operator import itemgetter

a = [{"id":1,"data":{"age":16,"name":"a"}}, 
     {"id":3,"data":{"age":35,"name":"b"}}, 
     {"id":2,"data":{"age":9,"name":"c"}}]

l=sorted(a, key = lambda k : itemgetter('age')(itemgetter('data')(k)) )

print (l)
like image 81
Imane Fateh Avatar answered Nov 03 '22 22:11

Imane Fateh