Python 程序:从字典中移除指定键

编写一个 Python 程序,使用 if else 语句、del、keys 和 pop 函数,并通过实际示例从字典中删除指定的键。

Python 程序:使用 if else 从字典中移除指定键

在此程序中,我们使用 if 语句 来检查键是否存在于该 字典 中。在 If 语句内部,有一个 `del` 函数用于从该字典中删除键值对。

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)
Program to Remove Given Key from a Dictionary

使用 del 函数从字典中删除指定键

此程序是删除字典中键值的另一种方法。在这里,我们使用 keys 函数来查找 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'}

使用 pop 从字典中删除指定键

在此 程序 中,我们使用 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'}
>>>