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

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

问题描述

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

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'

我想要获得 foo

相同:

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

我该怎么做?

推荐答案

在字典中调用 list()

keys = list(test)

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

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天全站免登陆