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