Dictionary .keys() and .values() should return a set [with Python 3000 in mind]

Antoon Pardon apardon at forel.vub.ac.be
Tue Jul 4 03:36:28 EDT 2006


On 2006-07-01, cmdrrickhunter at yaho.com <conrad.ammon at gmail.com> wrote:
> There's a few good reasons.
> 1 - golden handcuffs.  Breaking old code is bad 90% of the time
> 2 - creating a set MAY be slower.
>
> Python's sets seem to imply to that they will always be a hash map.  in
> this case, some creative hash map "mapping" could allow one to create a
> set without calculating hash codes (make the set hashmap have the same
> dimentions and rules as the dictionary one).
> If there was intent to allow Python implementations to use trees for
> the set, then a list is far faster to create (O(n) time instead of
> O(nlogn)).
>
> 3 - using a set is sometimes slower (just as using a list is sometimes
> slower)
> I can't speak for your code, but this is the most common use of keys in
> my coding:

> # d is some dictionary
> keys = d.keys()
> keys.sort()
> for k in keys:
>   #blah

Wouldn't you be better of with a tree instead of dictionary? Maybe
there are other reasons to prefer a dict, but have a look at:

  http://www.pardon-sleeuwaegen.be/antoon/avltree.html

Suppose t is a tree implementing the same mapping a your dictionary
d above, the code would be:

  # t is some tree
  for k in t:
    #blah

And the keys will be treated in order.


If you try it, let me know what you think of it.

-- 
Antoon Pardon



More information about the Python-list mailing list