Skip to content

Instantly share code, notes, and snippets.

@ascavalcante80
Last active August 26, 2016 17:28
Show Gist options
  • Save ascavalcante80/2c5af315deab44bde1b7688004b2ed53 to your computer and use it in GitHub Desktop.
Save ascavalcante80/2c5af315deab44bde1b7688004b2ed53 to your computer and use it in GitHub Desktop.
sort python dictionaries by value
"""
This scripts give an example of how sort a dictionary by value. It prints the following tuples:
('grape', 1)
('banana',2)
('pineapple',3)
('apple',4)
"""
# by convention, this import should come in the first line, but I put here to make the example clear!
import operator
words = {'banana':2, 'apple':4, 'grape':1, 'pineapple':3}
sorted_words = sorted(words.items(), key=operator.itemgetter(1))
for item in sorted_words:
print(item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment