Python3中AttributeError: 'dict' object has no attribute 'has_key'的解决方案

当我在一次写下如下代码时,报错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更改为自己的设定值。

其实网上也有人说过这个问题,只不过在Python3的写法里,他只提供了一种,我这里加以补充。当然,如果你使用的是Python2,最上面的那种写法是没有问题的。

猜你喜欢

转载自blog.csdn.net/hfutdog/article/details/82319362