如果mydict不为空,则访问任意元素,如下:
mydict[mydict.keys()[0]]
还有什么更好的办法吗?
如果mydict不为空,则访问任意元素,如下:
mydict[mydict.keys()[0]]
还有什么更好的办法吗?
当前回答
子类化字典是一种方法,但效率不高。这里如果你提供一个整数,它将返回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'
其他回答
另一种方法是在一行中做到这一点,同时保持字典的完整性:
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中简单地这样做:
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
没有外部库,适用于Python 2.7和3.x:
>>> list(set({"a":1, "b": 2}.values()))[0]
1
对于任意键,省略.values()
>>> list(set({"a":1, "b": 2}))[0]
'a'
在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))