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

mydict[mydict.keys()[0]]

还有什么更好的办法吗?


当前回答

这个怎么样。这里还没有提到。

Py 2和Py 3

a = {"a":2,"b":3}
a[list(a)[0]] # the first element is here
>>> 2

其他回答

对于Python 2和3:

import six

six.next(six.itervalues(d))

另一种方法是在一行中做到这一点,同时保持字典的完整性:

arbitrary_value = mydict.setdefault(*mydict.popitem())

popitem() returns a tuple of (key, value) for the last item that was added into the dictionary and this pair is passed into setdefault as positional arguments. The setdefault tries to insert key into mydict with value value if it doesn't already exist, but does nothing if does exist; and then returns the value of that key to the caller. Because we already popped the (key, value) pair out of the dictionary, we insert it back into it via setdefault and then proceed to return value, which is what we want.

在python3中,方法是:

dict.keys() 

返回一个类型为:dict_keys()的值,当获取dict的key的第一个成员时,我们将得到一个错误:

dict.keys()[0]
TypeError: 'dict_keys' object does not support indexing

最后,我将dict.keys()转换为list @1st,并通过列表拼接方法获得了第一个成员:

list(dict.keys())[0]

为了得到钥匙

next(iter(mydict))

得到一个值

next(iter(mydict.values()))

两者兼得

next(iter(mydict.items())) # or next(iter(mydict.viewitems())) in python 2

前两个是Python 2和3。后两个在python3中是lazy,但在python2中不是。

在python3

list(dict.values())[0]