[Tutor] A sorted dictionary (of sorts)

ThreeBlindQuarks threesomequarks at proton.me
Thu Sep 29 18:05:12 EDT 2022


If one may ask, what is the great advantage of keeping a dictionary sorted? A major point in hashing something is to get access to any item in constant time.

Python once stated dictionaries had no pre-defined guaranteed order but that has changed and there is one that keeps the keys in the order they were added.

If you want keys sorted alphabetically or numerically or sorted by values, you can simply create a function to sort them when you want to use them such as in an iterable. Changes in Python would not easily break your access function.

Some people have created hash-like objects extend dictionaries in many ways and you could do that too.

- 3




Sent with Proton Mail secure email.

------- Original Message -------
On Thursday, September 29th, 2022 at 10:29 AM, Ed Connell <edwinconnell at gmail.com> wrote:


> 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
> 
> --
> 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!
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list