Multi field sorting on python dictionaries



We might come into a scenario when we need to use not only one but two, three or more attributes to sort a list or dictionary in Python (similar to order by field1, field2, field3… analogy in SQL).

Take the below dictionary example...


{'a': 2, 'b': 3, 'c': 2, 'd': 1, 'e': 1}

The sorted output desired is below:

d 1
e 1
a 2
c 2
b 3

Note that the first sort order is on the [value] ascending and second sort order is on ascending alphabetical order of the [key]. This can be achieved as shown in the following snippet:

alphabet_count = {'a': 2, 'b': 3, 'c': 2, 'd': 1, 'e': 1}
for key in sorted(alphabet_count.keys(), key=lambda x:(alphabet_count[x], x), reverse=False):
     print(key, alphabet_count[key])

Now, what if the desired output is on descending [value] and ascending [key] as below:

b 3
a 2
c 2
d 1
e 1

We can tweak the sign on the [value] field to reach at a solution. Eg.

alphabet_count = {'a': 2, 'b': 3, 'c': 2, 'd': 1, 'e': 1}
for key in sorted(alphabet_count.keys(), key=lambda x:(-alphabet_count[x], x), reverse=False):
     print(key, alphabet_count[key])

In short, it is key to remember to group the sorting attributes in order in a tuple i.e. (x, y, ..) format in the lambda function.


Comments

Popular Posts