为什么dict.has_key()在Python中不起作用?

时间:2018-01-03 04:36:16

标签: python-3.x dictionary python-2.x

示例:

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

收益TRUE,但

Dict.has_key("Age")

给出错误。为什么???

3 个答案:

答案 0 :(得分:2)

在Python 3.x中删除了

has_keys()

只使用仍然优于in

has_keys()

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

答案 1 :(得分:0)

has_key()方法位于Python2。它在Python3中不可用。

dir()函数可以返回字典对象上定义的方法。

您可以按照以下方式检查两个版本中has_key()的可用性,

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'
>>> 

因此,您可以尝试以下代码来检查字典中是否存在键。

它适用于Python2Python3两者。

>>> 
>>> # 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
>>> 

答案 2 :(得分:-1)

因为删除了Python 3.x has_keys()func, 很容易就可以使用“if else”替换它

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

def has_key(key, data)    
    return key in data