【问题标题】:Why dict.has_key() does not work in Python? [duplicate]为什么 dict.has_key() 在 Python 中不起作用? [复制]
【发布时间】:2018-01-03 04:36:15
【问题描述】:

例子:

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

产生TRUE,但是

Dict.has_key("Age")

给出错误。为什么会这样??

【问题讨论】:

  • 如果由于某种原因确实需要该方法,in 的功能由__contains__ 方法定义

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


【解决方案1】:

has_keys() 在 Python 3.x 中被移除

只需使用仍然比has_keys() 更好的in

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2013-02-03
      • 2022-12-11
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      相关资源
      最近更新 更多