在 Python 中访问字典中的任意元素 [英] Access an arbitrary element in a dictionary in Python

查看:37
本文介绍了在 Python 中访问字典中的任意元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 mydict 不为空,我访问任意元素为:

If a mydict is not empty, I access an arbitrary element as:

mydict[mydict.keys()[0]]

有没有更好的方法来做到这一点?

Is there any better way to do this?

推荐答案

在 Python 3 上,以非破坏性和迭代方式:

On Python 3, non-destructively and iteratively:

next(iter(mydict.values()))

在 Python 2 上,以非破坏性和迭代方式:

On Python 2, non-destructively and iteratively:

mydict.itervalues().next()

如果你想让它在 Python 2 和 3 中工作,你可以使用 six 包:

If you want it to work in both Python 2 and 3, you can use the six package:

six.next(six.itervalues(mydict))

虽然在这一点上它很神秘,我更喜欢你的代码.

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 = mydict.popitem()

请注意,first"在这里可能不是一个合适的术语,因为 dict 不是 Python 中的有序类型 <3.6.Python 3.6+ dicts 是有序的.

Note that "first" may not be an appropriate term here because dict is not an ordered type in Python < 3.6. Python 3.6+ dicts are ordered.

这篇关于在 Python 中访问字典中的任意元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆