关于字典:为什么dict.has_key()在python中不起作用?

Why dict.has_key() does not work in Python?

本问题已经有最佳答案,请猛点这里访问。

例如: 红血丝

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

TRUEYIELDS,但 红血丝

1
Dict.has_key("Age")

给出了错误。为什么是这样的吗???????? 红血丝


在python 3.x中删除了has_keys()

只需使用仍优于has_keys()in

src:https://docs.python.org/3.1/whatsnew/3.0.html内置


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

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

您可以检查两个版本中has_key()的可用性,如下所示:

Python 2.7.13

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.62.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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都有效。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
>>>
>>> # 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
>>>


因为python 3.x已经删除了u keys()func,很容易,你可以用"如果有的话"来代替它

https://docs.python.org/3.1/whatsnew/3.0.html内置

1
2
def has_key(key, data)    
    return True if key in data else False