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

"Martin v. Löwis" martin at v.loewis.de
Wed Nov 23 19:34:02 EST 2005


Christoph Zwerschke wrote:
> Anyway, I was thinking about whether it would be possible and desirable 
> to change the old behavior in future Python versions and let dict.keys() 
> and dict.values() both return sets instead of lists.

You answer the question whether it would be possible (no, because of
backwards compatibility); you don't attempt to answer the question
whether it would be desirable. Why do you think that would be
a good idea?

If you want the set of keys of a dictionary d, then do set(d):

 >>> d={1:2,3:4}
 >>> set(d)
set([1, 3])

As Mike Meyer explains, the same is meaningless for .values():
they might not be unique. For .items(), conversion into a set
does would appear to be meaningful, but doesn't actually work:
if the values contain unhashable objects, the set of tuples
cannot be constructed (as set members must be immutable).

Regards,
Martin



More information about the Python-list mailing list