Skip to content

Instantly share code, notes, and snippets.

@etigui
Last active October 14, 2020 12:08
Show Gist options
  • Save etigui/a859a33b810c1ecfd4a9f288c5bbca7a to your computer and use it in GitHub Desktop.
Save etigui/a859a33b810c1ecfd4a9f288c5bbca7a to your computer and use it in GitHub Desktop.
Python - sort dict
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