如何檢查 Python 字典中是否存在某個鍵?
字典以無序且可變的方式維護唯一鍵到值的對映。在 Python 中,字典是一種獨特的資料結構,資料值使用字典儲存在鍵值對中。字典用花括號編寫,幷包含鍵和值。
從 Python 3.7 開始,字典是有序的。Python 3.6 及更早版本中的字典未排序。
示例
在以下示例中,companyname 和 tagline 是鍵,Tutorialspoint 和 simplyeasylearning 分別是值。
thisdict = { "companyname": "Tutorialspoint", "tagline" : "simplyeasylearning", } print(thisdict)
輸出
以上程式碼產生以下結果
{'companyname': 'Tutorialspoint', 'tagline': 'simplyeasylearning'}
在本文中,我們將檢查字典中是否存在某個鍵。為此,有多種方法,下面將討論每種方法。
使用 in 運算子
我們使用“in”運算子來檢查字典中是否存在該鍵。
如果鍵存在於給定的字典中,“in”運算子返回“True”,如果鍵不存在於字典中,則返回“False”。
示例 1
以下示例使用 in 運算子來檢查給定字典中是否存在特定鍵。
this_dict = { "companyname" : "Tutorialspoint", "tagline" : "simplyeasylearning" , 'location': 'India'} if "companyname" in this_dict: print("Exists") else: print("Does not exist") if "name" in this_dict: print("Exists") else: print("Does not exist")
輸出
生成的輸出如下所示。
Exists Does not exist
示例 2
以下是另一個示例:
示例 2
以下是另一個示例:
my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'} print('name' in my_dict) print('foo' in my_dict)
輸出
這將給出以下輸出:
True False
使用 get() 方法
在這種方法中,我們使用 get() 方法來了解鍵是否存在於字典中。get() 方法返回具有指定鍵的專案的 value。
語法
這是 Python 中 get() 方法的語法。
dict.get(key,value)
其中,
- key - 您要從中檢索值的 object 的鍵名。
- value - 如果給定的鍵不存在,則返回此值。預設值為 None。
示例 1
此示例顯示了 Python 中可用的 get() 方法的使用。
this_dict = { "companyname" : "Tutorialspoint", "tagline" : "simplyeasylearning" , 'location': 'India'} if this_dict.get("tagline") is not None: print("Exists") else: print("Does not exist") if this_dict.get("address") is not None: print("Exists") else: print("Does not exist")
輸出
執行以上程式碼時生成的輸出如下所示。
Exists Does not exist
廣告