写一个 Python示例从字典中删除给定的键,并给出一个实例。
在这个 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示例是从字典中删除键值的另一种方法。这里,我们使用键功能在字典中查找一个键。
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 程序中,我们使用 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'}
>>>
标签: 自媒体