首页 > 编程知识 正文

Python 程序:从字典中删除给定键

时间:2023-11-25 09:12:53 阅读:308960 作者:YTEY

写一个 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'}
>>> 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。