Skip to content

Instantly share code, notes, and snippets.

@andyxning
Last active November 11, 2015 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyxning/a8f94546a013eb64419e to your computer and use it in GitHub Desktop.
Save andyxning/a8f94546a013eb64419e to your computer and use it in GitHub Desktop.
Sort a Dict in Python
#/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