Last active
October 14, 2020 12:08
-
-
Save etigui/a859a33b810c1ecfd4a9f288c5bbca7a to your computer and use it in GitHub Desktop.
Python - sort dict
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
mydict = {"carl": 40,"alan": 2,"bob": 1,"danny": 3} | |
# Sort a dict by key | |
for key in sorted(mydict.keys()): | |
print("%s: %s" % (key, mydict[key])) | |
# OUTPUT | |
alan: 2 | |
bob: 1 | |
carl: 40 | |
danny: 3 | |
# Sort a dict by value | |
for key, value in sorted(mydict.items(), key=lambda item: item[1]): | |
print("%s: %s" % (key, value)) | |
# OUTPUT | |
bob: 1 | |
alan: 2 | |
danny: 3 | |
carl: 40 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment