Python Forum
Sort Differences in 2.7 and 3.10 Explained
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sort Differences in 2.7 and 3.10 Explained
#1
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}
Reply
#2
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).
dgrunwal likes this post
Reply
#3
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.
dgrunwal likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Tutorial 4.4 Loop Explained rts 2 818 Sep-26-2022, 07:46 PM
Last Post: rts
  Calculate the sum of the differences inside tuple PUP280 4 1,149 Aug-12-2022, 07:20 PM
Last Post: deanhystad
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,277 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  Newbie - code solution explained Stjude1982 2 1,790 Sep-16-2021, 08:54 AM
Last Post: Stjude1982
  How to compare two PDFs for differences Normanie 2 2,351 Jul-30-2020, 07:31 AM
Last Post: millpond
  Condition check differences and how to organise code? adam2020 4 2,629 May-12-2019, 04:12 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020