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

创新互联python教程:

10年积累的做网站、成都网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站设计后付款的网站建设流程,更有柘荣免费网站建设让你可以放心的选择与我们合作。

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

当前名称:Python程序:从字典中删除给定键
文章源于:http://www.hantingmc.com/qtweb/news30/284330.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联