Python 3 字典不包含 dict.has_key() 方法

Python 3 中移除了字典的 has_key() 方法,如果你有代码使用了 has_key(),要么就改用 Python 2,要么就建议使用 in 操作。这也是 Python 官方文档给出的 Python 3 的若干变化之一。今天正好用到了 OrderedDict,搜了下网上代码都是 Python 2 的,于是在此记录一下。

一、has_key() in Python 3

如下阐述:

has_key was removed in Python 3. From the documentation:

  • Removed dict.has_key() – use the in operator instead.

Here’s an example:

if start not in graph:
    return None

也就是说,之后可以用 in 和 not in 来判断字典中是否有某个特定值。

二、参考文献和其他

参考:

  • https://stackoverflow.com/questions/33727149/dict-object-has-no-attribute-has-key/33727186
  • https://docs.python.org/3.0/whatsnew/3.0.html#builtins

学无止境,学海无涯。


【AD】炭云:768元/年/1GB内存/20GB SSD空间/2TB流量/500Mbps-1Gbps端口/独立IPv4/KVM/广州移动

【AD】美国洛杉矶CN2 VPS/香港CN2 VPS/日本CN2 VPS推荐,延迟低、稳定性高、免费备份_搬瓦工vps