Walk through dictionary keys?

Tim Peters tim.one at home.com
Wed Dec 20 02:18:35 EST 2000


[Emile van Sebille]
> I'm not sure when or how long this has been in, but the cvs
> version of dict's has a popitem method that looks like it does
> what you want.
>
> d = {1:11,2:22,3:33,4:44}
> for i in xrange(len(d)):
>      print d.popitem()

[Tim Roberts]
> But is popitem destructive?  That is, when that loop is complete, is
> d empty?

Yes, d is empty.  It's not like Perl's "each" that way (which is what the
original poster asked about); OTOH, .popitem() is well-defined if d is
mutated inside the loop.

The original motivation for .popitem() was in the use of dicts to implement
sets.  Many set algorithms are of the form:

   while myset:   # would "not myset.empty()" really be clearer?!
       e = myset.pick_some_element()
       myset.remove(e)
       # deal with e, possibly adding more stuff to myset

There is no efficient way to implement the "pick an element and remove it"
operation in Python 2.0 if the set is represented as a dict.  .popitem()
provides one.

I expect it will also be handy for iterating over huge dicts not used to
represent sets; it's common enough for the last operation on a dict to be

    stuff = dict.items()
    for k, v in stuff:
        yadda

.popitem() can be used instead if dict is dead at this point, and so avoid
the memory burden of materializing a full list of (key, value) pairs.

.popitem()-is-the-right-answer-to-questions-that-weren't-
    asked-ly y'rs  - tim





More information about the Python-list mailing list