TypeError: 'type' object is not subscriptable in Python 3.x

Dung Do Tien Oct 13 2021 151

Hello you guys, I beginner in Python and I'm also studying more about Python.

I write some line of code help me understand more about object in Python. My code as below:

cat = dict[1]
dog = dict[2]
bird = dict[3]

dict = {1: "cat.png", 2: "dog.png", 3: "bird.png"}

print(cat)
print(dog)
print(bird)

But I get an exception throw TypeError: 'type' object is not subscriptable when I run code above.

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    cat = dict[1]
TypeError: 'type' object is not subscriptable

My code  does not have any variable with name 'type'. It's realy too diffecult to understand.

And I am using python 3.8.2

Anyone can explain it to me? 

How can I solve it?

Thanks for any suggestions.

Have 1 answer(s) found.
  • D

    Devx Mon Oct 13 2021

    'type' is not a name of variable :D.

    You need to remember the rule "Declare before use it". So you need declare object before use it. You can see code below:

    dict = {1: "cat.png", 2: "dog.png", 3: "bird.png"}
    
    cat = dict[1]
    dog = dict[2]
    bird = dict[3]
    
    print(cat)
    print(dog)
    print(bird)

    #Output

    cat.png
    dog.png
    bird.png

    I hope it clear for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close