Python Forum

Full Version: Sort Differences in 2.7 and 3.10 Explained
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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}
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).
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.