【发布时间】:2013-09-04 07:26:53
【问题描述】:
我正在尝试通过索引访问 dict_key 的元素:
test = {'foo': 'bar', 'hello': 'world'}
keys = test.keys() # dict_keys object
keys.index(0)
AttributeError: 'dict_keys' object has no attribute 'index'
我想得到foo。
与:
keys[0]
TypeError: 'dict_keys' object does not support indexing
我该怎么做?
【问题讨论】:
-
在 py3.x
dict.keys()中返回一个类似视图对象的集合,而不是列表(因此,无法进行索引)。使用keys = list(test) -
当我做 list(something_dict) 时,元组顺序是随机的:例如:list({'foo': 'bar', 'hello': 'world'}) 可以返回:list(foo , hello) 或 list(hello, foo),为什么这是随机的?
-
Dicts don't have any order.(如果您想要订购的钥匙,请使用
collections.OrderedDict) -
关于线程安全的有趣讨论在这里重新讨论解决此问题的各种方法:blog.labix.org/2008/06/27/…
标签: python dictionary python-3.x key