Table of Contents
Reproducing TypeError: ‘dict_values object is not subscriptable
When you try to access the dict_values object through index, the error will raise stating TypeError: 'dict_values' object is not subscriptable
. Here is the example below.
1 2 3 4 |
my_dict = {'a': 1, 'b': 2, 'c': 3} print(my_dict.values()[0]) |
1 2 3 4 5 6 7 8 |
TypeError Traceback (most recent call last) <ipython-input-4-eb4c6bca4286> in <module> 1 my_dict = {'a': 1, 'b': 2, 'c': 3} ----> 2 print(my_dict.values()[0]) TypeError: 'dict_values' object is not subscriptable |
Convert dict_values object to list
To resolve TypeError: 'dict_values object is not subscriptable, convert dict_values object to list before accessing it using index.
Let’s take an example that uses the list() function to convert the dict_values
object into a list.
1 2 3 4 5 |
my_dict = {'a': 4, 'b': 5, 'c': 6} values_list = list(my_dict.values()) print(values_list) |
1 2 3 |
[4, 5, 6] |
Here, we used the dictionary’s values()
method to get a dict_values
object containing all the values. Then, we enclosed the dict_values
object within the list()
method to change its type from dict_values
to list
, which we stored in the values_list
variable.
Finally, we used the print()
method to display values_list
.
The values of the dictionaries can be accessed through the key
or the values()
method. In addition, the specific value of the dictionary can be accessed or can retrieve all the values. Use the following methods to access the Dictionary
values.
Using Key to Access Specific Value of Dictionary
Use the specified key to retrieve the particular value of the dictionary in Python.
1 2 3 4 5 |
my_dict = {'a': 1, 'b': 2, 'c': 3} value_b = my_dict['b'] print(value_b) |
1 2 3 |
2 |
First, we defined the dictionary named my_dict
with three key-value pairs 'a': 1, 'b': 2, 'c': 3
. Then, we accessed the specific value 2
from the dictionary using its key 'b'
. Finally, we used the print()
method to print the value of 'b'
on the output screen, which is 2
.
Using for
Loop with .values()
Method to Access All Values
Use the for
loop with the .values()
method to retrieve all values of the dictionary in Python.
1 2 3 4 5 |
my_dict = {'a': 1, 'b': 2, 'c': 3} for value in my_dict.values(): print(value) |
1 2 3 4 5 |
1 2 3 |
To access all the values in a dictionary, we can use a loop or convert the dict_values
object into a list or a tuple; we used the for
loop for the above code, iterated over the dictionary and printed the values against all keys. In this method, the built-in values()
method is used to get all values.
To conclude, convert dict_values object to list, use the key to access a specific value or the loop to iterate over all the values using the values()
method.
That’s all about how to resolve TypeError: ‘dict_values’ Object Is Not Subscriptable in Python.