python 字典get的键不存在_处理Python字典中的缺失键

在Python中,有一个称为字典的容器。在字典中,我们可以将键映射到其值。使用字典可以在恒定时间内访问值。但是,如果不存在给定的键,则可能会发生一些错误。

在本节中,我们将看到如何处理此类错误。如果我们尝试访问丢失的键,则可能会返回这样的错误。

范例程式码

country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'}

print(country_dict['Australia'])

print(country_dict['Canada']) # This will return error

输出结果AU

---------------------------------------------------------------------------

KeyErrorTraceback (most recent call last)

 in ()

2

3 print(country_dict['Australia'])

----> 4 print(country_dict['Canada'])# This will return error

KeyError: 'Canada'

使用get()Method处理KeyError

我们可以使用get方法检查键。此方法有两个参数。第一个是键,第二个是默认值。找到键后,它将返回与键关联的值,但是当键不存在时,它将返回默认值,该默认值将作为第二个参数传递。

范例程式码

country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'}

print(country_dict.get('Australia', 'Not Found'))

print(country_dict.get('Canada', 'Not Found'))

输出结果AU

Not Found

使用setdefault()Method处理KeyError

该setdefault()方法类似于该get()方法。它也需要两个参数,例如get()。第一个是键,第二个是默认值。此方法的唯一区别是,当缺少键时,它将添加具有默认值的新键。

范例程式码

country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'}

country_dict.setdefault('Canada', 'Not Present') #Set a default value for Canada

print(country_dict['Australia'])

print(country_dict['Canada'])

输出结果AU

Not Present

使用defaultdict

defaultdict是一个容器。它位于Python的collections模块中。defaultdict将默认工厂用作其参数。最初,默认工厂设置为0(整数)。如果不存在键,它将返回默认工厂的值。

我们不需要一次又一次地指定方法,因此它为字典对象提供了更快的方法。

范例程式码

import collections as col

#set the default factory with the string 'key not present'

country_dict = col.defaultdict(lambda: 'Key Not Present')

country_dict['India'] = 'IN'

country_dict['Australia'] = 'AU'

country_dict['Brazil'] = 'BR'

print(country_dict['Australia'])

print(country_dict['Canada'])

输出结果AU

Key Not Present

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值