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

Christoph Zwerschke cito at online.de
Fri Nov 25 01:35:11 CET 2005


Martin v. Löwis wrote:

> It follows from what is documented. set(<iterable object>) creates a
> set that contains all elements in the iterable object:
> http://docs.python.org/lib/built-in-funcs.html#l2h-63
> Now, is a dictionary an iterable object? Yes, it is:
> http://www.python.org/peps/pep-0234.html
> Together, this gives the property I demonstrated.

You need to know a third thing, namely that as an iterable object, a 
dictionary returns the keys only, not the key/value tuples which would 
also make some sense. If it had been designed that way, you could write

for k, v in d:
	print k, v

instead of:

for k in d:
	print k, d[k]

What I wanted to say is that the doco could mention this possibility to 
get the keys as a set at the place where it explains the keys() method.

-- Christoph



More information about the Python-list mailing list