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

M.-A. Lemburg mal@lemburg.com
Thu, 30 Nov 2000 14:40:12 +0100


Michael Hudson wrote:
> 
> 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.

Just curious: how would you get at the deleted value when
using .popfirstkey() ?

But you have a point: dict.pop() returning the first filled slot
in the dictionary as tuple (key,value) would probably be most
effective. It's also nice and short.

BTW, I don't get the inspiration for the "first" part in those
names... it makes you think that there's an order to dictionary
items when in reality there isn't.

> 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).

No, the point is that you can modify the dictionary within
the loop. You wouldn't see any changes using the second technique.

-- 
Marc-Andre Lemburg
______________________________________________________________________
Company:                                        http://www.egenix.com/
Consulting:                                    http://www.lemburg.com/
Python Pages:                           http://www.lemburg.com/python/