'Dict' Object has no attribute 'has_key' in Python3

Asked

Viewed 3,840 times

5

In Python 2, when I wanted to know if a dict had certain key, I used the method has_key.

if kwargs.has_key("code"):
   self.code = kwargs.code

However, now that I ran the same script in Python 3, I got the following error:

Attributeerror: 'Dict' Object has no attribute 'has_key'

In Python 3, this method has_key has been removed? What option do I have now?

1 answer

9


The method dict.has_key was removed in Python 3.x, use the operator in.

Removed. dict.has_key() - use the in Operator Instead.

In your case, you can use it like this:

if "code" in kwargs:
   self.code = kwargs.code
  • Cool. Apparently, this gives more performance, since instead of a method will use an operator..

  • 1

    Performance is exactly the same- operators in Python usually call internal methods. (in this case, the method __contains__ ) - but the rewrite is to use the syntax with in even in Python 2.

  • @jsbueno thank you so much for the information. I didn’t know it was possible to use in in Python 2. I always thought that "the right one" was the has_key.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.