problem: you want to sort the list based on the values in one or more dictionaries
Solution: It is very easy to sort such structures using the Itemgetter () function in the operator module.
#Sort A list of a dicts on a common keyrows= [ {'fname':'Brian','lname':'Jones','UID': 1003}, {'fname':'David','lname':'Beazley','UID': 1002}, {'fname':'John','lname':'Cleese','UID': 1001}, {'fname':'Big','lname':'Jones','UID': 1004}] fromoperatorImportItemgetterrows_by_fname= sorted (rows, Key=itemgetter ('fname')) Rows_by_uid= sorted (rows, Key=itemgetter ('UID')) fromPprintImportPprintPrint("Sorted by fname:") Pprint (rows_by_fname)#the Pprint () of the Pprint module provides a way to print out any Python data structure class and method. Print("Sorted by UID:") Pprint (rows_by_uid) rows_by_lfname= sorted (rows, Key=itemgetter ('lname','fname'))Print("Sorted by Lname,fname:") Pprint (rows_by_lfname)
>>> ================================ RESTART ================================>>>Sorted by fname:[{'fname':'Big','lname':'Jones','UID': 1004}, {'fname':'Brian','lname':'Jones','UID': 1003}, {'fname':'David','lname':'Beazley','UID': 1002}, {'fname':'John','lname':'Cleese','UID': 1001}]sorted by uid:[{'fname':'John','lname':'Cleese','UID': 1001}, {'fname':'David','lname':'Beazley','UID': 1002}, {'fname':'Brian','lname':'Jones','UID': 1003}, {'fname':'Big','lname':'Jones','UID': 1004}]sorted by lname,fname:[{'fname':'David','lname':'Beazley','UID': 1002}, {'fname':'John','lname':'Cleese','UID': 1001}, {'fname':'Big','lname':'Jones','UID': 1004}, {'fname':'Brian','lname':'Jones','UID': 1003}]>>>
Additional notes:
Lambda expressions are sometimes used to replace the Itemgetter () function: But using itemgetter () will run faster, so if you consider performance, you should use Itemgetter ().
Rows_by_fname = sorted (rows, key=lambda r:r['fname'= sorted (rows, key =Lambda r:r['uid'])
Finally, the techniques presented in this section also apply to functions such as min () and Max ():
>>> min (Rows, Key=itemgetter ('UID')){'lname':'Cleese','fname':'John','UID': 1001}>>> max (rows, Key=itemgetter ('UID')){'lname':'Jones','fname':'Big','UID': 1004}>>> itemgetter (' uid ')
<operator.itemgetter Object at 0x023532f0>
>>>
"Python Cookbook" "Data Structure and algorithm" 13. Sort the list of dictionaries by public key