Python Forum
Sort Differences in 2.7 and 3.10 Explained - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Sort Differences in 2.7 and 3.10 Explained (/thread-37047.html)



Sort Differences in 2.7 and 3.10 Explained - dgrunwal - Apr-26-2022

Python coders,

Is there a particular reason/change that causes this sort result between versions? How common is this kind of change in Python? Do most people just incrementally test their code in each new version?

Best,
David


2.7

>>> d = {'IN':2, 'GE':2, 'AK':3, 'BEG':1}
>>> n_l = sorted(d.items(), key=lambda x: (x[1], len(x[0]), x[0]))
>>> new_d = {k:v for k,v in n_l}
>>> new_d
{'AK': 3, 'GE': 2, 'BEG': 1, 'IN': 2}
3.10

>>> d = {'IN':2, 'GE':2, 'AK':3, 'BEG':1}
>>> n_l = sorted(d.items(), key=lambda x: (x[1], len(x[0]), x[0]))
>>> new_d = {k:v for k,v in n_l}
>>> new_d
{'BEG': 1, 'GE': 2, 'IN': 2, 'AK': 3}



RE: Sort Differences in 2.7 and 3.10 Explained - jefsummers - Apr-26-2022

Looking at it, I believe the difference is not in sorted, but rather in the order of the dictionary. Early versions of Python did not guarantee the order of items in a dictionary. And, indeed, your result is clearly not sorted in 2.7 (not supported in many years).


RE: Sort Differences in 2.7 and 3.10 Explained - deanhystad - Apr-27-2022

I agree. Print n_1 and the values will be sorted correctly. The old dictionary order is probably determined by the hash value of the keys.