Python: How to sort a list of dictionaries by several values? -


i want sort list @ first value , second value. there easy way this? here small example:

a = [{'name':'john','age':45},      {'name':'andi','age':23},      {'name':'john','age':22},      {'name':'paul','age':35},      {'name':'john','age':21}] 

this command sorting list 'name':

sorted(a, key = lambda user: user['name']) 

but how can sort list second value? 'age' in example.

i want sorting (first sort 'name' , sort 'age'):

andi - 23 john - 21 john - 22 john - 45 paul - 35 

thanks!

>>> = [{'name':'john','age':45},      {'name':'andi','age':23},      {'name':'john','age':22},      {'name':'paul','age':35},      {'name':'john','age':21}] >>> sorted(a, key = lambda user: (user['name'], user['age'])) [{'age': 23, 'name': 'andi'}, {'age': 21, 'name': 'john'}, {'age': 22, 'name': 'john'}, {'age': 45, 'name': 'john'}, {'age': 35, 'name': 'paul'}] 

this sorts tuple of 2 attributes, following equivalent , faster/cleaner:

>>> operator import itemgetter >>> sorted(a, key=itemgetter('name', 'age')) [{'age': 23, 'name': 'andi'}, {'age': 21, 'name': 'john'}, {'age': 22, 'name': 'john'}, {'age': 45, 'name': 'john'}, {'age': 35, 'name': 'paul'}] 

from comments: @bakuriu

i bet there not big difference between two, itemgetter avoids bit of overhead because extracts keys , make tuple during single opcode(call_function), while calling lambda have call function, load various constants(which other bytecodes) call subscript (binary_subscr), build tuple , return it... that's lot more work interpreter.

to summarize: itemgetter keeps execution on c level, it's fast possible.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -