Why is dictionary.keys() a list and not a set?

Christoph Zwerschke cito at online.de
Fri Nov 25 15:13:16 EST 2005


Mike Meyer schrieb:

> Ok, how about this for dictionaries/sets:
> 
> Any hashable object can be used as a dictionary key (set member). Immutable
> objects, except for tuples that contain a non-hashable object, are
> hashable. Python classes are normally hashable(1).

I would be even more simple here, like that:

The keys can be arbitrary immutable objects. Thus lists, sets or 
dictionaries are not allowed as keys. Tuples are allowed if they do not 
directly or indirectly contain mutable objects. More exactly, the keys 
are required to be hashable (1).

And then go on and define "hashable" in the footnot.

I think that is easy and understandable and covers the basic cases.

> And the footnote is:
> 
> Instances of Python classes are hashable if they define a __hash__
> method, or if they don't define either __cmp__ or __eq__.

I think that's not exact enough. For instance, ordinary lists also 
define a __hash__ method but are not hashable since that method just 
raises an exception. Also, as Martin pointed out, if both is there 
(__hash__ and __cmp__/__eq__) you would also require of a "proper" 
__hash__ method that equal objects hash the same. Otherwise, semantics 
would suffer, you could have dicts with non-unique keys (i.e. keys which 
are only distinct as objects, but not different as values).

-- Christoph



More information about the Python-list mailing list