在Python中访问字典中的任意元素 [英] Access an arbitrary element in a dictionary in Python
本文介绍了在Python中访问字典中的任意元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果 dict
不为空,我将访问任意元素:
If a dict
is not empty, I access an arbitrary element as:
dict[dict.keys()[0]]
有没有更好的方法这样做?
Is there any better way to do this?
推荐答案
非破坏性你可以:
dict.itervalues().next()
在Python 3上成为
On Python 3 this becomes
next (iter (dict.values()))
如果你希望它在Python 2& 3,您可以使用 6
库:
If you want it to work in both Python 2 & 3, you can use the six
library:
six.next(six.itervalues(dict))
虽然在这一点上它是相当神秘,我宁愿更喜欢你的代码。
though at this point it is quite cryptic and I'd rather prefer your code.
如果要删除任何项目,请执行以下操作:
If you want to remove any item, do:
key, value = dict.popitem()
请注意,第一不是一个合适的术语这里。这是任何项目,因为 dict
不是有序类型。
Note that "first" is not an appropriate term here. This is "any" item, because dict
is not an ordered type.
这篇关于在Python中访问字典中的任意元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文