Is it possible to sort a dictionary?

Carel Fellinger cfelling at iae.nl
Thu Mar 29 17:46:02 EST 2001


Alex Martelli <aleaxit at yahoo.com> wrote:
> "Carel Fellinger" <cfelling at iae.nl> wrote in message
> news:99q70i$1le$1 at animus.fel.iae.nl...
>     [snip]
>> I just wonder why the items() method is slooow; values() and keys()
>> are both much faster, going over the whole dict indexing from keys()
>> is even faster.  Is tuple making/unpacking so expensive?  Or is a dict

> I can't reproduce this observation... here's a datapoint:

> sortWithItems: 0.0438600314118
...
> sortWithKeys: 0.0460969072614

> i.e., items() seems a bit _faster_ than keys() then

hm, so it seems.

> going over the dict -- with the script b.py being:

> def sortWithKeys(adict):
>     keys = adict.keys()
>     keys.sort()
>     return [ (key, adict[key]) for key in keys ]

Ah, but besides going over the dict indexing from keys() you're
building an items list here too:) If you make a list of only the
values instead of key,value tuples, it will be the faster one.

And that's what surprised me.  I expected items() to be faster then
the combination of dict.keys(); [dict[key] for key in dict.keys] as
items is all done in C and the alternative is mostly done in Python.
E.g., in items there is no need to check that dict is still the same
for each key, but in the Python loop, dict has to be looked-up for
each key.  Somehow I thought that such things would make up for the
building of tuples.

-- 
groetjes, carel



More information about the Python-list mailing list