了解如何利用PythonDict判斷字典中是否存在指定鍵

Python 中的字典(Dict)是一種資料結構,它是一種鍵值對(key-value)的集合,可以快速查找和更新資料。本文將介紹如何使用 Python Dict 判斷字典中是否存在指定鍵。

使用 in 運算子判斷字典中是否存在指定鍵

Python 提供了 in 運算子,可以用來判斷字典中是否存在指定鍵。下面的範例展示了如何使用 in 運算子來判斷字典中是否存在指定鍵:

my_dict = {
    'name': 'John',
    'age': 30
}

if 'name' in my_dict:
    print('Name key exists in the dictionary')
else:
    print('Name key does not exist in the dictionary')

上面的程式碼會判斷字典中是否存在名為 name 的鍵,如果存在則輸出 Name key exists in the dictionary,如果不存在則輸出 Name key does not exist in the dictionary。

使用 get() 方法判斷字典中是否存在指定鍵

Python 也提供了 get() 方法,可以用來判斷字典中是否存在指定鍵。下面的範例展示了如何使用 get() 方法來判斷字典中是否存在指定鍵:

my_dict = {
    'name': 'John',
    'age': 30
}

if my_dict.get('name') is not None:
    print('Name key exists in the dictionary')
else:
    print('Name key does not exist in the dictionary')

上面的程式碼會判斷字典中是否存在名為 name 的鍵,如果存在則輸出 Name key exists in the dictionary,如果不存在則輸出 Name key does not exist in the dictionary。

總結

本文介紹了如何使用 Python Dict 判斷字典中是否存在指定鍵,可以使用 in 運算子或是 get() 方法來判斷字典中是否存在指定鍵。

發佈留言