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

mydict[mydict.keys()[0]]

还有什么更好的办法吗?


当前回答

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

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中不是。

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 现在字典是按插入顺序排列的。

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

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.

first_key, *rest_keys = mydict

你可以做:

for k in sorted(d.keys()):
    print d[k]

这将为您提供一个一致排序的键集(我猜是相对于builtin.hash()),如果排序对您有任何意义,您可以对其进行处理。这意味着,例如,即使扩展字典,数值类型也会保持一致排序。

例子

# lets create a simple dictionary
d = {1:1, 2:2, 3:3, 4:4, 10:10, 100:100}
print d.keys()
print sorted(d.keys())

# add some other stuff
d['peter'] = 'peter'
d['parker'] = 'parker'
print d.keys()
print sorted(d.keys())

# some more stuff, numeric of different type, this will "mess up" the keys set order
d[0.001] = 0.001
d[3.14] = 'pie'
d[2.71] = 'apple pie'
print d.keys()
print sorted(d.keys())

请注意,字典在打印时是排序的。但是键集本质上是一个hashmap!