[Tutor] A sorted dictionary (of sorts)

Ed Connell edwinconnell at gmail.com
Fri Sep 30 14:06:24 EDT 2022


Thanks for the reassurance, Roel.

On Thu, Sep 29, 2022 at 6:42 PM Roel Schroeven <roel at roelschroeven.net>
wrote:

> Ed Connell schreef op 29/09/2022 om 16:29:
> > Hi,
> >
> > The following works fine, but it always made me nervous because
> > ordinary dictionaries  are not supposed  to be sorted.  It works (for
> > now).  Should I worry that some new version of python will break things?
> >
> >      # produce a sorted dictionary
> >      sorted_names = sorted( Team_Calc_d, key = lambda e: Team_Calc_d[ e
> > ].current_power,
> >          reverse = True ) # sorted by current power
> >      TeamPwrSorted_Result_d = {}
> >      for tm in sorted_names:
> >          # setup SortTeams_PowerResult_Dict and copy from Analysis
> objects
> >          # to Results objects
> >          TeamPwrSorted_Result_d[ tm ] = Results( Team_Basics_d[ tm
> > ].start_power )
> >          # create the dictionary
> >          TeamPwrSorted_Result_d[ tm ].current_power = Team_Calc_d[ tm
> > ].current_power
> >
> >      needs_processing = False # we just updated
> >
> >      return TeamPwrSorted_Result_d
> These days Python dictionaries are ordered (which is not the same as
> sorted), meaning that they preserve the order in which keys were
> inserted. This was already the case in version 3.6 of the CPython
> implementation, but since version 3.7 dictionary order is guaranteed to
> be insertion order in all conforming implementations.
>
> You sort the keys before you insert the items, and you then insert them
> in that order, so everything is fine.
>
> Since that behavior is now guaranteed, you can rely on it. Should it
> ever change, which is very unlikely, there would be a depreciation
> period to give everybody the chance to fix things.
>
> --
> "The saddest aspect of life right now is that science gathers knowledge
> faster than society gathers wisdom."
>          -- Isaac Asimov
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


-- 
I have a right and a left brain, but there is nothing right in the left one
and there is nothing left in the right one!


More information about the Tutor mailing list