There are several different ways to check if a Python dictionary contains a specific key, i.e.
d = {}
if key in d:
if d.contains(key开发者_JAVA技巧):
if d.has_key(key):
it's silly for a language to allow you to do the same thing several different ways, UNLESS, each of the methods was doing something entirely different. Could someone please contrast the three techniques above, how are they different?
They're all the same and they're all around for historical reasons, but you should use key in d
.
Method #1 is the accepted way to do it. Method #2 doesn't actually exist, at least in any versions of Python that I'm aware of; I'd be interested to see where you found that. Method #3 used to be the accepted way, but is now deprecated.
So there really is just one way.
d.__contains__(key)
is what is used it key in d
(since in
operator calls __contains__
method of the dictionary)
has_key
is deprecated and does the same as __contains__
key in d
is the accepted way to do it.__contains__
is the ‘“magic” attribute’ (ref) that implements the above syntax. Most, if not all, special syntax is implemented via such methods. E.g., thewith
statement is implemented via__enter__
and__exit__
. Such methods exist for allowing special functionality to be provided for user-defined classes.the
has_key
method no longer exists in Python 3 and is deprecated in Python 2.
精彩评论