TypeError: 'dict_values' object is not subscriptable in Python
Dung Do Tien Jun 01 2022 514
Hi everyone. Today is the third day I'm learning Python and I want to learn about objects and arrays. I was trying to create an object and read all keys and values of it by using values()
and keys()
methods, like this:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
my_obj = {'name': name, 'age': age}
lstValue = my_obj.values()
lstKey = my_obj.keys()
print(lstKey[0] + "= " + lstValue[0])
print(lstKey[1] + "= " + lstValue[1])
But when running the app after entering a name and age I got an exception TypeError: 'dict_values' object is not subscriptable.
Enter your name: python
Enter your age: 32
Traceback (most recent call last):
File "main.py", line 8, in <module>
print(lstValue[0] + "= " + lstKey[0])
TypeError: 'dict_values' object is not subscriptable
I'm using VS 2022 and Python version 3.9.7.
Please help me if you know any solution!
Thanks in advance.
Have 1 answer(s) found.
- P0
Pramod Pal Jun 01 2022
The
my_obj.keys()
andmy_obj.values()
methods return an object, not an array. So you can not access it by index.Solution: use
list()
built-in method to help convert an object to an array. See example:name = input("Enter your name: ") age = int(input("Enter your age: ")) my_obj = {'name': name, 'age': age} lstValue = list(my_obj.values()) lstKey = list(my_obj.keys()) print(lstKey[0] + "= " + lstValue[0]) print(lstKey[1] + "= " + str(lstValue[1]))
#Output
Enter your name: Python Enter your age: 33 name= Python age= 33
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.