Python 字典(Dictionary) __contains__(key)方法

时间:2025-03-17 10:17:44

Python 2 中字典(Dictionary) has_key() 函数用于判断键是否存在于字典中,如果键在字典dict里返回true,否则返回false。

使用如下:   dict.has_key(key)

举个栗子:   dict = {'Name':'coco','Sex':'Female'}  # 定义字典

                       print(dict.has_key('Name'))   # True

                       print(dict.has_key('Age'))    # False

Python 3 中字典(Dictionary) has_key() 函数变为 __contains__(key),用法一样,举个栗子:

                      dict = {'Name':'coco','Sex':'Female'}  # 定义字典

                      print(dict.__contains__('Name'))   # True