attributeerror: dict object has no attribute has_key

Cause of attributeerror: dict object has no attribute has_key

The “Attributeerror: ‘dict’ object has no attribute has_key” happens because in Python 3. The ‘has_key( )’ method has been removed.

So in Python 3, we use the ‘in‘ operator instead of has_key( ).

 

 

Here is an example of why this error occurs

languages = {'python':'Version 3', 'java':'Version 1'}

# Here we will see the AttributeError: 'dict' object has no attribute 'has_key'

if lang.has_key('java'):
    print('Present in languages')

Output:

attributeerror: dict object has no attribute has_key

 

 

 

Now we can fix the above program by simply changing the if condition and adding ‘in‘ operator.

languages = {'python':'Version 3', 'java':'Version 1'}

# Checking if the key is present in lang dictionary

if 'java' in lang:
    print('Present in languages')

Output:

The ‘in‘ operator is used for checking whether the key is present or not in the dictionary in python. If the key is present in the dictionary, then it returns True, else it returns False.

 

 

Same as we can use the ‘not in’ operator for checking the key is not present in the dictionary in python. If the key is not present in the dictionary, then it returns True, else it returns False.

languages = {'python':'Version 3', 'java':'Version 1'}

# Checking if the key is present in lang dictionary

if 'php' not in lang:
    print('Not Present in languages')
else:
    print('Present in languages')

Output:

 

 

Conclusion: So ‘dict‘ objects don’t have now a ‘has_key( )‘ function, so the error is caused.

 

Also, read our Python Tutorials.

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *