处理Python字典中缺少的键

在python中, 字典 将一个键映射到其值的容器是否具有访问时间复杂性 O(1) 但在许多应用程序中,用户并不知道字典中的所有键。在这种情况下, 如果用户试图访问丢失的密钥,则会弹出一个错误,指示密钥丢失 .

null

Python3

# Python code to demonstrate Dictionary and
# missing value error
# initializing Dictionary
d = { 'a' : 1 , 'b' : 2 }
# trying to output value of absent key
print ( "The value associated with 'c' is : " )
print (d[ 'c' ])


错误:

Traceback (most recent call last):  File "46a9aac96614587f5b794e451a8f4f5f.py", line 9, in     print (d['c'])KeyError: 'c'

在上面的示例中,字典中没有名为“c”的键出现运行时错误。为了避免这种情况,并让用户知道某个特定的密钥不存在,或者在该位置弹出默认消息,有几种方法可以处理丢失的密钥。

方法1:使用get()

获取(键,定义值) 方法在我们必须检查密钥时非常有用。如果存在密钥,则打印与密钥相关的值,否则返回传入参数的def_值。

例子:

Python3

country_code = { 'India' : '0091' ,
'Australia' : '0025' ,
'Nepal' : '00977' }
# search dictionary for country code of India
print (country_code.get( 'India' , 'Not Found' ))
# search dictionary for country code of Japan
print (country_code.get( 'Japan' , 'Not Found' ))


输出:

0091Not Found

方法2:使用setdefault()

设置默认值(键、定义值) 其工作方式与get()类似,但区别在于每次 如果缺少密钥,将创建一个新密钥 与传入参数的键关联的def_值。

例子:

Python3

country_code = { 'India' : '0091' ,
'Australia' : '0025' ,
'Nepal' : '00977' }
# Set a default value for Japan
country_code.setdefault( 'Japan' , 'Not Present' )
# search dictionary for country code of India
print (country_code[ 'India' ])
# search dictionary for country code of Japan
print (country_code[ 'Japan' ])


输出:

0091Not Present

方法3:使用defaultdict

defaultdict “是在名为的模块中定义的容器” 收藏 “.需要一段时间。” 函数(默认工厂)作为其参数 .默认情况下 默认工厂设置为“int”,即0 .如果 钥匙不在 在defaultdict中 返回默认出厂值 展示。它比get()或setdefault()有优势。

  • 默认值设置为 公告 .有 不需要 反复调用函数,并将类似的值作为参数传递。因此 节省时间 .
  • defaultdict的实现是 更快 而不是get()或setdefault()。

例子:

Python3

# Python code to demonstrate defaultdict
# importing "collections" for defaultdict
import collections
# declaring defaultdict
# sets default value 'Key Not found' to absent keys
defd = collections.defaultdict( lambda : 'Key Not found' )
# initializing values
defd[ 'a' ] = 1
# initializing values
defd[ 'b' ] = 2
# printing value
print ( "The value associated with 'a' is : " ,end = "")
print (defd[ 'a' ])
# printing value associated with 'c'
print ( "The value associated with 'c' is : " ,end = "")
print (defd[ 'c' ])


输出:

The value associated with 'a' is : 1The value associated with 'c' is : Key Not found

本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享