Python3 - 测试dictionary字典中是否存在某个key

Python3 - 测试dictionary字典中是否存在某个key

如果没有判断 key 是否在 dict 中,而直接访问,则会报错:KeyError: ‘key’。 可通过 in 操作符判定,语法如下

1
2
if key in dict:
    do something

测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
def main():
    fruits = {
        'apple':1,
        'orange':2,
        'banana':3
    }

	#if key 'apple' exists in fruits?
    if 'apple' in fruits:
        print(fruits['apple'])

if __name__ == '__main__':
    main()

控制台输出:

1
2
$ python3 main.py
$ 1

上述代码在 python3.7.6 测试通过

Rating: