我试图通过其索引访问 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
我怎样才能做到这一点?
原文由 fj123x 发布,翻译遵循 CC BY-SA 4.0 许可协议
改为在字典上调用
list()
:在 Python 3 中,
dict.keys()
方法返回一个 字典视图对象,它充当一个集合。直接遍历字典也会产生键,因此将字典转换为列表会得到所有键的列表: