Python dictionary check for specific keys

There are several ways to check if a Python dictionary contains a specific key, i.e.

d = {} if key in d: if d.contains(key): if d.has_key(key): 

This is stupid for a language that allows you to do the same thing in several different ways: UNLESS, each of the methods did something completely different. Can anyone contrast the three methods above, how do they differ?

+6
source share
4 answers

d.__contains__(key) - this is what key in d (because the in operator calls the __contains__ method of the dictionary)

has_key deprecated and does the same as __contains__

+5
source

They are all the same and they are all around for historical reasons, but you should use key in d .

+12
source

Method # 1 is an accepted way to do this. Method # 2 does not actually exist, at least in any versions of Python that I know of; I would be interested to know where you found it. Method 3 was a recognized method, but now deprecated .

Thus, there is only one way.

+7
source
  • key in d is an accepted way to do this.

  • __contains__ is a magic attribute ( ref ) that implements the above syntax. Most, if not all, special syntax is implemented using such methods. For example, the with statement is implemented through __enter__ and __exit__ . Such methods exist to enable the provision of special functions for custom classes.

  • The has_key method no longer exists in Python 3 and is deprecated in Python 2.

+4
source

Source: https://habr.com/ru/post/896156/


All Articles