Last active
November 11, 2015 08:55
-
-
Save andyxning/a8f94546a013eb64419e to your computer and use it in GitHub Desktop.
Sort a Dict in Python
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
#/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
a = {3:4, 1:2, 5:6} | |
# Demo1 | |
# | |
# get a list of tuples consisting the dict, | |
# sort the list with tuple items | |
print sorted(a.items()) | |
# sort according to key | |
# print sorted(d.items(), key=lambda t: t[0]) | |
# sort according to value | |
# print sorted(d.items(), key=lambda t: t[1]) | |
# Demo2 | |
# | |
print [key, a.get(key) for key in sorted(a.iterkeys())] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment