gpt4 book ai didi

python - 在 Python3 中按索引访问 dict_keys 元素

转载 作者:行者123 更新时间:2023-12-03 17:37:36 24 4
gpt4 key购买 nike

我正在尝试通过索引访问 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

我怎样才能做到这一点?

最佳答案

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

keys = list(test)

在 Python 3 中, dict.keys()方法返回 dictionary view object ,作为一个集合。直接迭代字典也会产生键,因此将字典转换为列表会产生所有键的列表:
>>> test = {'foo': 'bar', 'hello': 'world'}
>>> list(test)
['foo', 'hello']
>>> list(test)[0]
'foo'

关于python - 在 Python3 中按索引访问 dict_keys 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45221640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com