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
?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With