Created
April 10, 2015 14:12
-
-
Save Averroes/094287215bba8bac76ff to your computer and use it in GitHub Desktop.
sort a list of dictionaries by a common key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # example.py | |
| # | |
| # Sort a list of a dicts on a common key | |
| rows = [ | |
| {'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 itemgetter | |
| rows_by_fname = sorted(rows, key=itemgetter('fname')) | |
| rows_by_uid = sorted(rows, key=itemgetter('uid')) | |
| from pprint import pprint | |
| print("Sorted by fname:") | |
| pprint(rows_by_fname) | |
| 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment