如果mydict不为空,则访问任意元素,如下:
mydict[mydict.keys()[0]]
还有什么更好的办法吗?
如果mydict不为空,则访问任意元素,如下:
mydict[mydict.keys()[0]]
还有什么更好的办法吗?
当前回答
first_key, *rest_keys = mydict
其他回答
在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]
对于Python 2和3:
import six
six.next(six.itervalues(d))
子类化字典是一种方法,但效率不高。这里如果你提供一个整数,它将返回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'
忽略字典排序的问题,这样可能会更好:
next(dict.itervalues())
这样就避免了项查找和生成不使用的键的列表。
Python3
next(iter(dict.values()))
这个怎么样。这里还没有提到。
Py 2和Py 3
a = {"a":2,"b":3}
a[list(a)[0]] # the first element is here
>>> 2