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

mydict[mydict.keys()[0]]

还有什么更好的办法吗?


当前回答

如果你只需要访问一个元素(碰巧是第一个元素,因为字典不保证顺序),你可以在Python 2中简单地这样做:

my_dict.keys()[0]    # key of "first" element
my_dict.values()[0]  # value of "first" element
my_dict.items()[0]   # (key, value) tuple of "first" element

请注意(据我所知)Python不能保证连续两次调用这些方法中的任何一个都会返回相同顺序的list。Python3不支持这一点。

在Python 3中:

list(my_dict.keys())[0]    # key of "first" element
list(my_dict.values())[0]  # value of "first" element
list(my_dict.items())[0]   # (key, value) tuple of "first" element

其他回答

first_key, *rest_keys = mydict

忽略字典排序的问题,这样可能会更好:

next(dict.itervalues())

这样就避免了项查找和生成不使用的键的列表。

Python3

next(iter(dict.values()))

为了得到钥匙

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]

As others mentioned, there is no "first item", since dictionaries have no guaranteed order (they're implemented as hash tables). If you want, for example, the value corresponding to the smallest key, thedict[min(thedict)] will do that. If you care about the order in which the keys were inserted, i.e., by "first" you mean "inserted earliest", then in Python 3.1 you can use collections.OrderedDict, which is also in the forthcoming Python 2.7; for older versions of Python, download, install, and use the ordered dict backport (2.4 and later) which you can find here.

Python 3.7 现在字典是按插入顺序排列的。