-2

Example:

Dict={"Name":"Sai","Age":23}
"Age" in Dict

Yields TRUE, but

Dict.has_key("Age")

Gives error. Why is that??

smci
  • 32,567
  • 20
  • 113
  • 146
Sai Kumar Reddy
  • 75
  • 1
  • 2
  • 5
  • If you really need the method for some reason, the functionality of `in` is defined by the [`__contains__`](https://docs.python.org/3/reference/datamodel.html#object.__contains__) method – Patrick Haugh Jan 03 '18 at 04:45

2 Answers2

7

has_keys() was removed in Python 3.x

just use in that still was better than has_keys()

src: https://docs.python.org/3.1/whatsnew/3.0.html#builtins

SunriseM
  • 985
  • 9
  • 15
0

The has_key() method is in Python2. It is not available in Python3.

dir() function can return the methods defined on the dictionary object.

You can check availability of has_key() in both the versions as I did as follows,

Python 2.7.13

hygull@hygull:~$ python
Python 2.7.12 (default, Nov 20 2017, 18:23:56) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> dir(dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
>>> 
>>> # Checking the index of 'has_key' in the above list
...
>>> dir(dict).index("has_key")
32
>>> 
>>> Dict = {"Name": "Sai", "Age": 23};
>>> print (Dict.has_key("Age"))
True
>>> 

Python 3.6.2

hygull@hygull:~$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> 
>>> Dict = {"Name": "Sai", "Age": 23}
>>> print(Dict.has_key("Age"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'has_key'
>>> 

So you can try the following code to check the existence of keys in dictionary.

It will work on Python2 and Python3 both.

>>> 
>>> # Defining a dictionary
... 
>>> Dict = {"Name": "Sai", "Age": 23};
>>> 
>>> # 1st way to check existence of key using get() method defined on dictionary object
... 
>>> if Dict.get("Age"):
...     print (Dict.get("Age"));
... else:
...     print ("key \"Age\" does not exist in Dict.")
... 
23
>>> 
>>> if Dict.get("Age2"):
...     print (Dict.get("Age2"));
... else:
...     print ("key \"Age2\" does not exist in Dict.")
... 
key "Age2" does not exist in Dict.
>>> 
>>> 
>>> # 2nd way to check existence of key using try-catch statement(Exception handling concept)
...
>>> try:
...     print (Dict["Age2"])
... except KeyError:
...     print ("key \"Age2\" does not exist in Dict.")
... 
key "Age2" does not exist in Dict.
>>> 
>>> try:
...     print (Dict["Age"])
... except KeyError:
...     print ("key \"Age\" does not exist in Dict.")
... 
23
>>> 
hygull
  • 8,464
  • 2
  • 43
  • 52