Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3 [duplicate]
This is my code:
{names[i]:d.values()[i] for i in range(len(names))}
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?
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))}
A simpler version of your code would be:
dict(zip(names, d.values()))
If you want to keep the same structure, you can change it to:
vlst = list(d.values())
{names[i]: vlst[i] for i in range(len(names))}
(You can just as easily put list(d.values())
inside the comprehension instead of vlst
; it's just wasteful to do so since it would be re-generating the list every time).