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

Michael Hudson mwh21@cam.ac.uk
30 Nov 2000 14:06:58 +0000


"M.-A. Lemburg" <mal@lemburg.com> writes:
> Michael Hudson wrote:
> > 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() ?

You wouldn't.  I was thinking of the dict-as-sets code that was being
flung around earlier.

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

Yes.

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

I was trying to make an analogy between .firstkey/.firstitem and
.keys/.items - the 

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

was meant to be compared to 

    for k in dict.keys():
        ...

Sorry for being obscure.

Cheers,
M.

-- 
  "declare"?  my bogometer indicates that you're really programming
  in some other language and trying  to force Common Lisp into your
  mindset.  this won't work.            -- Erik Naggum, comp.lang.lisp