Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

EDIT:

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.

EDIT:

Unfortunately in P3K, .items() returns a dict_items object, unlike Python 2 which returned an iterator:

ActivePython 3.1.2.4 (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
like image 324
max Avatar asked Oct 23 '10 06:10

max


1 Answers

k, v = next(iter(d.items())) # updated for Python 3
like image 139
eumiro Avatar answered Sep 23 '22 17:09

eumiro