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

10年積累的做網(wǎng)站、成都網(wǎng)站設(shè)計經(jīng)驗(yàn),可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先網(wǎng)站設(shè)計后付款的網(wǎng)站建設(shè)流程,更有柘榮免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
寫一個 Python 程序從字典中刪除給定的鍵,并給出一個實(shí)例。
從字典中刪除給定鍵的 Python 程序示例 1
在這個 python 程序中,我們使用 if 語句來檢查這個字典中是否存在這個鍵。在 If 中,有一個 del 函數(shù)可以從字典中刪除鍵值。
# 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 函數(shù)從字典中移除密鑰。
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程序:從字典中刪除給定鍵
標(biāo)題網(wǎng)址:http://www.5511xx.com/article/cdhisgj.html


咨詢
建站咨詢
