Created
May 9, 2019 15:24
-
-
Save ferminhg/3c8787870cca64fbda40a5b1e6db2b6d to your computer and use it in GitHub Desktop.
Sort dict by value
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
| # How to sort a Python dict by value | |
| # (== get a representation sorted by value) | |
| >>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1} | |
| >>> sorted(xs.items(), key=lambda x: x[1]) | |
| [('d', 1), ('c', 2), ('b', 3), ('a', 4)] | |
| # Or: | |
| >>> import operator | |
| >>> sorted(xs.items(), key=operator.itemgetter(1)) | |
| [('d', 1), ('c', 2), ('b', 3), ('a', 4)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment