鍵(key) in 字典變數名稱
註:如果存在會回傳 True ,反之回傳 False
範例:
- # -*- coding: utf-8 -*-
- """
- Created on Tue Jan 29 21:14:39 2019
- @author: 軟體罐頭
- """
- stock = {'1101':'台泥','1103':'嘉泥','1104':'環泥','1108':'幸福','1109':'信大','1110':'東泥'}
- if not('1102' in stock):
- stock['1102']='亞泥'
- print('1102 = ',stock['1102'])
程式說明:
第10行:判斷1102是否存在stock字典中,如果不存在,就新增1102至stock字典
執行結果: