当前分类:300例题>>正文

Python示例:从字典中删除给定键

来源:互联网   更新时间:2023年6月24日  

Python 示例

写一个 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://6yhj.com/leku-p-4442.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 自媒体