在 Python3 中按索引访问 dict_keys 元素 [英] Accessing dict_keys element by index in Python3

查看:40
本文介绍了在 Python3 中按索引访问 dict_keys 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过索引访问 dict_key 的元素:

test = {'foo': 'bar', 'hello': 'world'}keys = test.keys() # dict_keys 对象键.index(0)AttributeError: 'dict_keys' 对象没有属性 'index'

我想要foo.

同:

键[0]类型错误:'dict_keys' 对象不支持索引

我该怎么做?

解决方案

改为在字典上调用 list() :

keys = list(test)

在 Python 3 中,dict.keys() 方法返回一个 字典视图对象,作为一个集合.直接迭代字典也会产生键,因此将字典转换为列表会产生所有键的列表:

<预><代码>>>>test = {'foo': 'bar', 'hello': 'world'}>>>列表(测试)['foo', '你好']>>>列表(测试)[0]'富'

I'm trying to access a dict_key's element by its index:

test = {'foo': 'bar', 'hello': 'world'}
keys = test.keys()  # dict_keys object

keys.index(0)
AttributeError: 'dict_keys' object has no attribute 'index'

I want to get foo.

same with:

keys[0]
TypeError: 'dict_keys' object does not support indexing

How can I do this?

解决方案

Call list() on the dictionary instead:

keys = list(test)

In Python 3, the dict.keys() method returns a dictionary view object, which acts as a set. Iterating over the dictionary directly also yields keys, so turning a dictionary into a list results in a list of all the keys:

>>> test = {'foo': 'bar', 'hello': 'world'}
>>> list(test)
['foo', 'hello']
>>> list(test)[0]
'foo'

这篇关于在 Python3 中按索引访问 dict_keys 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆