Python字典(dict)元素是否存在

Python字典(dict)元素是否存在

Python 中,判断 字典 中的某个元素是否存在使用 in 语句或者 not in 语句,如果键存在,in 语句返回 True,如果键不存在,in 语句返回 False。

字典元素是否存在详解

语法

key in dic

参数

参数 描述
dic 需要判断的字典。
key 需要检测的 key。

返回值

如果 key 存在,则返回 True,否则,返回 False。

说明

判断键 key 是否存在字典 dic 中。

python字典元素是否不存在详解

语法

key not in dic

参数

参数 描述
dic 需要判断的字典。
key 需要检测的 key。

返回值

如果 key 不存在,则返回 True,否则,返回 False。

说明

判断键 key 是否不存在字典 dic 中。

案例

in 语句判断字典键存在

使用 in 语句判断字典键存在

print("嗨客网(www.haicoder.net)") # 使用 in 语句判断字典键存在 dic = {"Name": "HaiCoder", "Age": 100, "Score": 99.5} print("Key In =", "Name" in dic) print("Key In =", "name" in dic)

程序运行后,控制台输出如下:

109 python字典dict元素存在.png

我们使用 {} 创建了一个字典 dic,字典中有三个元素,接着,我们使用 in 判断键 “Name” 是否存在字典 dic 中,键 “Name” 存在,因此返回 True。

最后,我们再次使用 in 判断键 “name” 是否存在字典 dic 中,键 “name” 不存在,因此返回 False。

not in 语句判断字典键存在

使用 not in 语句判断字典键存在

print("嗨客网(www.haicoder.net)") # 使用 in 语句判断字典键存在 dic = {"Name": "HaiCoder", "Age": 100, "Score": 99.5} print("Key Not In =", "Name" not in dic) print("Key Not In =", "name" not in dic)

程序运行后,控制台输出如下:

110 python字典dict元素存在.png

我们使用 {} 创建了一个字典 dic,字典中有三个元素,接着,我们使用 not in 判断键 “Name” 是否存在字典 dic 中,键 “Name” 存在,因此返回 False。

最后,我们再次使用 not in 判断键 “name” 是否存在字典 dic 中,键 “name” 不存在,因此返回 True。

Python字典(dict)元素是否存在总结

在 Python 中,判断字典中的某个元素是否存在使用 in 语句或者 not in 语句,如果键存在,in 语句返回 True,如果键不存在,in 语句返回 False。 Python 字典元素是否存在语法:

key in dic

Python 字典元素是否不存在语法:

key not in dic