Last active
August 26, 2016 17:28
-
-
Save ascavalcante80/2c5af315deab44bde1b7688004b2ed53 to your computer and use it in GitHub Desktop.
sort python dictionaries by value
This file contains 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
""" | |
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