Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to convert a dictionary into a subscriptable array?

I know how to convert a dictionary into an 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?

like image 323
quotable7 Avatar asked Nov 12 '15 14:11

quotable7


People also ask

Can we convert dictionary to array in Python?

To convert a dictionary to an array in Python, use the numpy. array() method, and pass the dictionary object to the np. array() method as an argument and it returns the array.

Are Dictionaries Subscriptable Python?

Since dict_values objects are not subscriptable, we can't access them at a specific index.

Can you turn a dictionary into a list Python?

In Python, a dictionary provides method items() which returns an iterable sequence of all elements from the dictionary. The items() method basically converts a dictionary to a list along with that we can also use the list() function to get a list of tuples/pairs.


3 Answers

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]) 
like image 144
Mazdak Avatar answered Oct 05 '22 17:10

Mazdak


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.

like image 31
Devansh Bansal Avatar answered Oct 05 '22 17:10

Devansh Bansal


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.)

like image 44
txsaw1 Avatar answered Oct 05 '22 17:10

txsaw1