AttributeError: 'dict' object has no attribute 'has_key' in Python

Dung Do Tien Jul 05 2022 356

Hello guys, I am a beginner in Python and I have created a small code that helps me print out all information of a tourist guide. I stored tourist info inside a dictionary.  It's simple like this:

tour_info = {'name':"Vietnam Day", 'price':1200, 'totalday':15, 'total visitor': 15 }
print("Hello, welcome to Vietnam tour \n")
print("Your tour name is :")
print(tour_info.has_key('name'))

print("You need to pay: $")
print(str(tour_info.has_key('price')))
print("in ")
print(str(tour_info.has_key('totalday')))

Data inside the dictionary might get from the database but in this example, I fixed it. 

But when running this code I got an exception AttributeError: 'dict' object has no attribute 'has_key'. Below is the detail of the exception:

Hello, welcome to Vietnam tour 

Your tour name is :
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(tour_info.has_key('name'))
AttributeError: 'dict' object has no attribute 'has_key'


** Process exited - Return Code: 1 **
Press Enter to exit terminal

I'm using Python 3.10 and ran on window 11.

Thanks in advance.

Have 1 answer(s) found.
  • D

    Dhiraj Goplani Jul 05 2022

    The Python interpreter throws the error because we are using Python 3. The dictionary method has_key()  only exists in Python 2. You can refer 2 solutions below:

    Solution 1

    Using in keyword to find a key in a dictionary. See the demo here:

    tour_info = {'name':"Vietnam Day", 'price':1200, 'totalday':15, 'total visitor': 15 }
    print("Hello, welcome to Vietnam tour \n")
    print("Your tour name is :")
    print('name' in tour_info) # will return true/false
    
    print("You need to pay: $")
    print('price' in tour_info) # will return true/false
    
    print("in ")
    print('totalday' in tour_info) # will return true/false

    #Output

    Hello, welcome to Vietnam tour 
    
    Your tour name is :
    True
    You need to pay: $
    True
    in 
    True

    Solution 2

    Change Python Major Version from 3 to 2.

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