Sorted dictionary

Chris Rebert clp2 at rebertia.com
Thu Jan 21 02:49:22 EST 2010


On Wed, Jan 20, 2010 at 5:50 PM, Steven D'Aprano
<steven at remove.this.cybersource.com.au> wrote:
> On Thu, 21 Jan 2010 02:02:02 +0100, Jan Kaliszewski wrote:
>
>> Hello,
>>
>> Inspired by some my needs as well as some discussions in the net, I've
>> implemented a sorted dictionary (i.e. a dict that returns keys, values
>> and items always sorted by keys):
>>
>> http://code.activestate.com/recipes/576998/
>
>
> What's the advantage of that over sorting the keys as needed?
>
>
> E.g.
>
> for key in sorted(dict):
>    print key
>
>
> works.

Well, it does spread out the cost of sorting the key list over each of
the N distinct key assignments, versus sorting the entire list all at
once, on-demand at the end of the process. And you avoid having to
traverse the M buckets in the dictionary to locate the N keys in the
first place. So it has different performance characteristics, which
could theoretically matter depending on the use case; e.g. it could
avoid a GUI application hanging for several seconds while it sorts a
large list of keys.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list