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

Mike Meyer mwm at mired.org
Fri Nov 25 04:15:32 CET 2005

"bonono at gmail.com" <bonono at gmail.com> writes:
> Christoph Zwerschke wrote:
>> jepler at unpythonic.net schrieb:
>> > You can already get a set from a dictionary's keys in an efficient manner:
>> >>>>l = dict.fromkeys(range(10))
>> >>>>set(l)
>> > Set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>> Good point. I expected that set(l) = set(l.items()) and not
>> set(l.keys()), but the latter would not work with mutable values. See
>> discussion with Martin.
> puzzled. items() return tuples which I believe can be element of set ?
> Or I misread you ?

Not all tuples can be elements of a set. Elements of a set have to be
hashable. Tuples compute their hash by hashing their contents. If
their contents aren't hashable, the tuple isn't hashable, and hence
can't be an element of a set. If the values in the dictionary aren't
hashable, then the tuples returned by items() won't be hashable
either, and hence can't be elements of a set.

Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list