pythonpython-3.xdictionarydictview

How to convert a dictionary into a subscriptable array?


I know how to convert a dictionary into a list in Python, but somehow when I try to get, say, the sum of the resulting list, I get the error 'dict_values' object is not subscriptable. Also, I plan to sum only several items in the list.

dict = {A:1, B:2, C:3, D:4}
arr = dict.values()
the_sum = sum(arr[1:3])

Upon closer inspection, I noticed that when the resulting list is printed out, it always gives dict_values(......) as the output which I can't remove. How do I get around this?


Solution

  • In Python 3, dict.values() doesn't return a list object like it used to in Python 2. Instead it returns a dict_values object which is a set-like object and uses a hash table for storing its keys 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])