新聞中心
這里有您想知道的互聯網營銷解決方案
Python程序:從字典中刪除給定鍵
創(chuàng)新互聯python教程:

10年積累的做網站、成都網站設計經驗,可以快速應對客戶對網站的新想法和需求。提供各種問題對應的解決方案。讓選擇我們的客戶得到更好、更有力的網絡服務。我雖然不認識你,你也不認識我。但先網站設計后付款的網站建設流程,更有柘榮免費網站建設讓你可以放心的選擇與我們合作。
寫一個 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'}
>>> 網站欄目:Python程序:從字典中刪除給定鍵
分享網址:http://m.fisionsoft.com.cn/article/cdhisgj.html


咨詢
建站咨詢
