Are these two sorting format exactly the same for dict sort in Python?

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
    print(x.keys())
    s1 = [item[0] for item in sorted(x.items(), key=lambda item: (item[1], item[0]), reverse=True)]
    s2 = [item[0] for item in sorted(x.items(), key=lambda item: item[1], reverse=True)]
    print(s1)
    print(s2)

The prints are:

dict_keys([1, 3, 4, 2, 0])
[3, 4, 1, 2, 0]
[3, 4, 1, 2, 0]

I usually use the 2nd way to sort a dict by value, but today I saw someone’s else code to sort a dict using the first way.

Are they exactly the same thing? They look the same based on print outs.

>Solution :

In this particular case, the results are identical because there is a bijection between the set of keys and the set of values. If several keys share the same value (example: keys 3 and 4 share the value 3) the results diverge, as here:

x = {1: 2, 3: 3, 4: 3, 2: 1, 0: 0}

Your code print:

dict_keys([1, 3, 4, 2, 0])
[4, 3, 1, 2, 0]
[3, 4, 1, 2, 0]

  • In s1 case, the dict is sorted on both values and keys so when 2 keys share a common value they are sorted too.

  • In s2 case only values are sorted. As sort algo is stable, when 2 keys share the same value their relative order is keeped in the result.

Leave a Reply