Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading