Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.