Sort a Python dictionary by value or key

Sort a dictionary by value in Python

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

mydict = {'jason':5,
sorted_dict_value = sorted(mydict.items(), key=operator.itemgetter(0))
[('jason', 5), ('michael', 3), ('sam', 6), ('terry', 1)]

Sort a dictionary by key in Python

import operator
sorted_dict_key = sorted(mydict.items(), key=lambda kv: kv[1])
[('terry', 1), ('michael', 3), ('jason', 5), ('sam', 6)]

Ace your next data science interview

Get better at data science interviews by solving a few questions per week

Learn more

Find a bug? Submit a suggested change on Github, or message me on Twitter.