天天看點

Python3 字典 in 操作符

Python3 字典

描述

Python 字典 in 操作符用于判斷鍵是否存在于字典中,如果鍵在字典 dict 裡傳回 true,否則傳回 false。

而 not in 操作符剛好相反,如果鍵在字典 dict 裡傳回 false,否則傳回 true。

文法

in 操作符文法:

key in dict
      

參數

  • key -- 要在字典中查找的鍵。

傳回值

如果鍵在字典裡傳回true,否則傳回false。

執行個體

以下執行個體展示了 in 操作符在字典中的使用方法:

執行個體(Python 3.0+)

#!/usr/bin/python3

thisdict = {'Name': 'Runoob', 'Age': 7}

# 檢測鍵 Age 是否存在

if 'Age' in thisdict:

print("鍵 Age 存在")

else :

print("鍵 Age 不存在")

# 檢測鍵 Sex 是否存在

if 'Sex' in thisdict:

print("鍵 Sex 存在")

print("鍵 Sex 不存在")

# not in

if 'Age' not in thisdict:

以上執行個體輸出結果為:

鍵 Age 存在
鍵 Sex 不存在
鍵 Age 存在