max max - 8 months ago 73
Python Question

non-destructive version of pop() for a dictionary

Is there any idiom for getting an arbitrary key, value pair from a dictionary without removing them? (P3K)


Sorry for the confusing wording.

I used the word arbitrary in the sense that I don't care about what I'm getting.

It's different from random, where I do care about what I'm getting (i.e., I need probabilities of each item being chosen to be the same).

And I don't have a key to use; if I did, I'd think it would be in the RTFM category and wouldn't deserve an answer on SO.


Unfortunately in P3K,

returns a
object, unlike Python 2 which returned an iterator:

ActivePython (ActiveState Software Inc.) based on
Python 3.1.2 (r312:79147, Sep 14 2010, 22:00:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {1:2}
>>> k,v = next(d.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: dict_items object is not an iterator

k, v = next(iter(d.items())) # updated for Python 3