Python sort dictionaries(dict) by key or values

By: Varghese Chacko 1 year, 2 months ago

Python dictionaries are  key-value pairs. Some times we need to sort the dictionary by key or by value. In both cases we can do it by using the built in sorted function.

Sort by keys:

Since normal dictionaries are not maintaining the order of keys, we can not create a new dictionary and maintain the order of keys. Instead we can always print (or do any other operation) in a loop by ordering items by key.

Example:

>>> d = {'A': 6, 'E': 3, 'D': 8, 'F': 9, 'i': 10, 'k': 11, 'q': 0, 'S': 7, 'r': 2, 'T': 4, 'w': 1, 'y': 5}
>>> for key in sorted(d):
...     print ("{key}: {value}".format(key=key, value=d[key]))
... 
A: 6
D: 8
E: 3
F: 9
S: 7
T: 4
i: 10
k: 11
q: 0
r: 2
w: 1
y: 5
>>> 

In the above  example, we sorted the dictionary in case-sensitive way and we can do it case-insensitive by specifying key method

Example:

>>> d = {'A': 6, 'E': 3, 'D': 8, 'F': 9, 'i': 10, 'k': 11, 'q': 0, 'S': 7, 'r': 2, 'T': 4, 'w': 1, 'y': 5}
>>> for key in sorted(d, key=str.lower):
...     print ("{key}: {value}".format(key=key, value=d[key]))
... 
A: 6
D: 8
E: 3
F: 9
i: 10
k: 11
q: 0
r: 2
S: 7
T: 4
w: 1
y: 5
>>>

Sort by Value:

To sort by value, we need to specify the value or get function as the key for the sorted

>>> d = {'A': 6, 'E': 3, 'D': 8, 'F': 9, 'i': 10, 'k': 11, 'q': 0, 'S': 7, 'r': 2, 'T': 4, 'w': 1, 'y': 5}
>>> for key in sorted(d, key=d.get):
...     print ("{key}: {value}".format(key=key, value=d[key]))
... 
q: 0
w: 1
r: 2
E: 3
T: 4
y: 5
A: 6
S: 7
D: 8
F: 9
i: 10
k: 11
>>>

here the get method of the dictionary is passed directly to the function. We can specify reverse=True to get it sorted reverse.