Search code examples
pythonsortingdictionarykeyalphabetical

Sorting keys of dictionary according to more than one criteria - Python 3.0


I'm trying to get a sorted dictionary. The dictionary should be sorted according to the following two criteria:

  1. According to the values (integers)
  2. If two keys (str) have the same value, sort alphabetically

So far, I have written the following line in my code:

sorted_word_values_dict = dict(sorted(word_values_dict.items(), key=operator.itemgetter(1)))

This code sorts correctly according to the first criteria, but if two keys (str) have the same value (e.g. both have a value of 2), they need to be sorted alphabetically. How can I include this extra criterium in my code?

Thanks in advance for any help!


Solution

  • You can use lambda as a key function in sorted call

    Following should get you the new dict in sorted order -

    sorted_word_values_dict = dict(sorted(word_values_dict.items(), key=lambda x: (x[1], x[0])))
    

    The key argument in sorted function can take a function which returns multiple values, in case there is a tie between the first value, the comparison would move to next value in the key.

    In this example, x[1](dict value) would be compared first, if it is identical, we would compare the x[0](dict key).