Python: how to convert a dictionary into a subscriptable array?
In python-3.X dict.values
doesn't return a list
object like how it used to perform in python-2.X. In python-3.x it returns a dict-value
object which is a set-like object and uses a hash table for storing its items which is not suitable for indexing. This feature, in addition to supporting most of set
attributes, is very optimized for operations like membership checking (using in
operator).
If you want to get a list object, you need to convert it to list by passing the result to the list()
function.
the_values = dict.values()
SUM = sum(list(the_values)[1:10])
Yes, it did appear like a list on the older Python questions asked here. But as @Kasramvd said, assuming you are using python 3.X, dict.values
is a dictionary view object.
(Also, you definitely came up with this example hastily as you have four dictionary entries but want 10 list items, which is redundant.)
By assigning dict.values()
to a list you are not converting it to a list; you are just storing it as dict_values (may be an object). To convert it write value_list=list(dict.values())
. Now even while printing the value_list
you will get the list elements and not dict_values(......)
.
And as mentioned before don't use Python built-in names as your variable names; it may cause conflicts during execution and confusion while reading your code.