popkey() method for dictionaries?

Fernando Pérez fperez528 at yahoo.com
Sun Nov 17 02:57:17 EST 2002


Hi all,

I've often found myself needing what I've called a popkey() function. Similar 
to the existing popitem() method, but which allows me to specify _which_ item 
I need via a key. This is what I've implemented (as a function), the code is 
trivial:

#----------------------------------------------------------------------------
class NotGiven: pass

def popkey(dct,key,default=NotGiven):
    """Return dct[key] and delete dct[key]. dct is modified in-place.

    If default is given, return it if dct[key] doesn't exist, otherwise raise
    KeyError.  """

    try:
        val = dct[key]
    except KeyError:
        if default is NotGiven:
            raise
        else:
            return default
    else:
        del dct[key]
        return val
#----------------------------------------------------------------------------

Do people think that this would be a worthwhile thing to have in the standard 
python dicts (as a method)? Basically I'm asking for opinions on whether it's 
a good/bad idea, and if it's considered good it could be sent to the 
developers. 

It could even be implemented as an extension to the existing popitem() method. 
Currently popitem() doesn't take any arguments, so the above 'key' argument 
could be made optional. 

What do people think? Good/bad? Useless to most?

Cheers,

f.



More information about the Python-list mailing list