Get: TypeError: 'dict_values' 对象在使用 python 3.2.3 时不支持索引 [英] Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3
问题描述
这是我的代码:
{names[i]:d.values()[i] for i in range(len(names))}
这在使用 python 2.7.3 时完全正常;但是,当我使用 python 3.2.3 时,我收到一条错误消息,指出 'dict_values' 对象不支持索引
.如何修改代码以使其兼容 3.2.3?
This works completely fine when using python 2.7.3; however, when I use python 3.2.3, I get an error stating 'dict_values' object does not support indexing
. How can I modify the code to make it compatible for 3.2.3?
推荐答案
在 Python 3 中,dict.values()
(连同 dict.keys()
和 dict.items()
) 返回一个 view
,而不是一个列表.请参阅此处的文档.因此,您需要将您对 dict.values()
的调用包装在对 list
的调用中,如下所示:
In Python 3, dict.values()
(along with dict.keys()
and dict.items()
) returns a view
, rather than a list. See the documentation here. You therefore need to wrap your call to dict.values()
in a call to list
like so:
v = list(d.values())
{names[i]:v[i] for i in range(len(names))}
这篇关于Get: TypeError: 'dict_values' 对象在使用 python 3.2.3 时不支持索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!