[Python-Dev] {}.getitem() (was Re: PEP-0218)

Michael Hudson mwh21@cam.ac.uk
30 Nov 2000 13:16:44 +0000


Guido van Rossum <guido@python.org> writes:

> > M.-A. Lemburg:
> > > Shouldn't be hard to do... the C API for this is already in place:
> > > PyDict_Next(). I'd prefer a method .getitem(), though, which then
> > > returns a tuple (key, value).
> > 
> > IMO '.pickitem()' would be a better name, since many people would
> > think, that 'getitem()' would take some kind of index as parameter.
> > Nevertheless I think this is a nice idea, though.
> 
> Pronouncement:
> 
> It is only efficient to get the *first* item, so let's make that
> explicit.  The method names will be:
> 
>  .firstkey()
>  .firstvalue()
>  .firstitem()
> 
> Moshe will check in a patch.
> 
> Thinking aloud:
> 
> Would it be useful to also implement popkey(), popvalue(), popitem(),
> which would remove the first item and then return the relevant part of
> it?

I must admit I can't think of a situation where .firstkey would be
more useful than .popkey; I thought that this discussion was
discussion was inspired by the wish to write code like:

while not set.empty():
    x = set.popfirstkey()
    ...

Maybe I'm jsut being dense, though.

FWIW, I think 

    dict.firstkey()

reads better than

    dict.firstitem()[0]

if the former's what you're actually trying to say.  Why not write

    for k,_ in dict.items():
        ...

? (Overstating the case slightly for effect, but I hope the point is
clear).

Cheers,
M.

-- 
  Arrrrgh, the braindamage!  It's not unlike the massively
  non-brilliant decision to use the period in abbreviations 
  as well as a sentence terminator.  Had these people no 
  imagination at _all_?                 -- Erik Naggum, comp.lang.lisp