草庐IT

python - 获取 : TypeError: 'dict_values' object does not support indexing when using python 3. 2.3

coder 2023-05-20 原文

这是我的代码:

{names[i]:d.values()[i] for i in range(len(names))}

这在使用 python 2.7.3 时完全正常;但是,当我使用 python 3.2.3 时,我收到一条错误消息,指出 'dict_values' 对象不支持索引。如何修改代码以使其与 3.2.3 兼容?

最佳答案

在 Python 3 中,dict.values()(连同 dict.keys()dict.items())返回一个view,而不是列表。请参阅文档 here .因此,您需要将对 dict.values() 的调用包装在对 list 的调用中,如下所示:

v = list(d.values())
{names[i]:v[i] for i in range(len(names))}

关于python - 获取 : TypeError: 'dict_values' object does not support indexing when using python 3. 2.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17431638/

有关python - 获取 : TypeError: 'dict_values' object does not support indexing when using python 3. 2.3的更多相关文章

随机推荐