寫一個 Python 程序從字典中刪除給定的鍵,並給出一個實例。
從字典中刪除給定鍵的 Python 程序示例 1
在這個 python 程序中,我們使用 if 語句來檢查這個字典中是否存在這個鍵。在 If 中,有一個 del 函數可以從字典中刪除鍵值。
# Python Program to Remove Given Key from a Dictionary
myDict = {'name': 'John', 'age': 25, 'job': 'Developer'}
print("Dictionary Items : ", myDict)
key = input("Please enter the key that you want to Delete : ")
if key in myDict:
del myDict[key]
else:
print("Given Key is Not in this Dictionary")
print("\nUpdated Dictionary = ", myDict)
從字典中刪除給定鍵的 Python 程序示例 2
這個 Python 程序是從字典中刪除鍵值的另一種方法。這裡,我們使用鍵功能在字典中查找一個鍵。
myDict = {'name': 'John', 'age': 25, 'job': 'Developer'}
print("Dictionary Items : ", myDict)
key = input("Please enter the key that you want to Delete : ")
if key in myDict.keys():
del myDict[key]
else:
print("Given Key is Not in this Dictionary")
print("\nUpdated Dictionary = ", myDict)
刪除字典鍵輸出
Dictionary Items : {'name': 'John', 'age': 25, 'job': 'Developer'}
Please enter the key that you want to Delete : name
Updated Dictionary = {'age': 25, 'job': 'Developer'}
從字典中刪除給定鍵的 Python 程序示例 3
在這個 python 程序中,我們使用 pop 函數從字典中移除密鑰。
myDict = {'name': 'John', 'age': 25, 'job': 'Developer'}
print("Dictionary Items : ", myDict)
key = input("Please enter the key that you want to Delete : ")
if key in myDict.keys():
print("Removed Item : ", myDict.pop(key))
else:
print("Given Key is Not in this Dictionary")
print("\nUpdated Dictionary = ", myDict)
刪除字典鍵輸出
Dictionary Items : {'name': 'John', 'age': 25, 'job': 'Developer'}
Please enter the key that you want to Delete : age
Removed Item : 25
Updated Dictionary = {'name': 'John', 'job': 'Developer'}
>>>
Dictionary Items : {'name': 'John', 'age': 25, 'job': 'Developer'}
Please enter the key that you want to Delete : sal
Given Key is Not in this Dictionary
Updated Dictionary = {'name': 'John', 'age': 25, 'job': 'Developer'}
>>>
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/239950.html