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 informati开发者_如何学运维on.
>>> 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
pop is supposed to remove a item. Isn't that the meaning of that method?
If you want to get random key , value pair use pseudo random module
>>> import random
>>> x = {1:3, 4:5, 6:7}
>>> x = {1:3, 4:5, 6:7, 'a':9, 'z':'x'}
>>> k = random.choice(x.keys())
>>> x[k]
7
>>>
The items()
method returns the copy of key, value pairs of dictionary as list. For example,
>fruits_color = {'apple': 'red', 'banana': 'green'}
>fruits_color.items()
[('apple', 'red'), ('banana', 'green')]
Once you have the list you can pick the key-value pairs.
import random
k, v = random.choice(d.items())
Get a "arbitrary" key-vaue pair?
k, v = k, d[k]
精彩评论