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

mydict[mydict.keys()[0]]

还有什么更好的办法吗?


当前回答

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

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.

其他回答

对于Python 2和3:

import six

six.next(six.itervalues(d))
first_key, *rest_keys = mydict

在Python 3中,非破坏性和迭代性:

next(iter(mydict.values()))

在Python 2中,非破坏性和迭代性:

mydict.itervalues().next()

如果你想让它在python2和python3中都能工作,你可以使用six包:

six.next(six.itervalues(mydict))

虽然在这一点上,它是相当神秘的,我更喜欢你的代码。

如果你想删除任何项目,请执行以下操作:

key, value = mydict.popitem()

请注意,“first”在这里可能不是一个合适的术语,因为dict在Python < 3.6中不是有序类型。Python 3.6+字典是有序的。

子类化字典是一种方法,但效率不高。这里如果你提供一个整数,它将返回d[list(d)[n]],否则按预期访问字典:

class mydict(dict):
    def __getitem__(self, value):
        if isinstance(value, int):
            return self.get(list(self)[value])
        else:
            return self.get(value)

d = mydict({'a': 'hello', 'b': 'this', 'c': 'is', 'd': 'a',
            'e': 'test', 'f': 'dictionary', 'g': 'testing'})

d[0]    # 'hello'
d[1]    # 'this'
d['c']  # 'is'

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