'dict' object has no attribute 'has_key'

发布时间 2023-04-11 18:23:44作者: He_LiangLiang

当我在一次写下如下代码时,报错AttributeError: 'dict' object has no attribute 'has_key':

if not my_dict.has_key(my_key):

 

当时真的是一脸懵逼,我在Python2的时候一直这样写的,为什么会错呢?

后来经过查询文档发现,在Python3中废除了dict的has_key()方法。

那么,如果我们还想实现上述语句的功能该怎么做呢?

有两种写法,一种是:

if my_key not in my_dict:

另外一种是:

if my_dict.get(my_key) is not None:

 

注意,这里的None是字典的默认值,如果你有其它设定,请将None更改为自己的设定值。