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

Steve Holden steve at holdenweb.com
Thu Nov 24 00:56:13 EST 2005


bonono at gmail.com wrote:
> jep... at unpythonic.net wrote:
> [...]
>>Maybe there are also other reasons to promise this property that I'm not
>>aware of.  Certainly it seems like this property is useful and not hard
>>to provide for "non-perverse" implementations, much like the
> 
> Thanks, but we don't need the list comprehension(or do we) ? As the
> return of d.iteritems() is already a list of tuples.
> 
No it isn't: it's a dictionary item iterator. This can be used to 
provide a list, but it's self-evidently an iterator, not a list:

  >>> d = dict.fromkeys(range(5))
  >>> d.iteritems
<built-in method iteritems of dict object at 0x4df604>
  >>> d.iteritems()
<dictionary-itemiterator object at 0x4e02e0>
  >>> [x for x in d.iteritems()]
[(0, None), (1, None), (2, None), (3, None), (4, None)]
  >>>

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list