字典的pop()的非破坏性版本 [英] non-destructive version of pop() for a dictionary
问题描述
有没有从字典中获取任意键,值对而不删除它们的习惯用法?(P3K)
Is there any idiom for getting an arbitrary key, value pair from a dictionary without removing them? (P3K)
对不起,措辞混乱.
我用任意这个词的意思是我不在乎得到的东西.
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).
而且我没有可使用的钥匙.如果这样做的话,我认为它将属于RTFM类别,因此不应该在SO上给出答案.
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.
不幸的是,在P3K中, .items()
返回一个 dict_items
对象,与Python 2不同,它返回了一个迭代器:
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
推荐答案
k, v = next(iter(d.items())) # updated for Python 3
这篇关于字典的pop()的非破坏性版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!