Python cookbook (data structure and algorithm) uses a public key to sort the dictionary list.
This example describes how to sort the dictionary list by using public keys in Python. We will share this with you for your reference. The details are as follows:
Problem:Sort the list by values in one or more dictionaries.
Solution:In the operator moduleitemgetter()
The function is very simple to sort such structures.
# 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}] from operator import itemgetterrows_by_fname = sorted (rows, key = itemgetter ('fname') rows_by_uid = sorted (rows, key = itemgetter ('uid') from pprint impo Rt pprintprint ("Sorted by fname:") pprint (rows_by_fname) # pprint module pprint () provides the ability to print out any python data structure classes and methods. 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}]>>>
Note:
Sometimes lambda expressions are used to replaceitemgetter()
Function: howeveritemgetter()
It will run faster, so we should useitemgetter()
.
rows_by_fname = sorted(rows, key=lambda r:r['fname'])rows_by_uid = sorted(rows, key=lambda r:r['uid'])
Finally, the technology shown in this section also appliesmin()
Andmax()
Such a function:
>>> 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>>>>
(The code is from Python Cookbook.)