Sort a Python dictionary by value or key
Python
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,
'terry':1,
'michael':3,
'sam':6}
sorted_dict_value = sorted(mydict.items(), key=operator.itemgetter(0))
sorted_dict_value
[('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])
sorted_dict_key
[('terry', 1), ('michael', 3), ('jason', 5), ('sam', 6)]