处理Python字典中缺少的键
在Python中,字典是将一个键映射到其值的容器,访问时间复杂度为O(1) 。但在许多应用程序中,用户并不知道字典中存在的所有键。在这种情况下,如果用户尝试访问丢失的键,则会弹出一个错误,指示丢失的键。
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'])
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'))
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'])
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'])
错误 :
Traceback (most recent call last):
File "46a9aac96614587f5b794e451a8f4f5f.py", line 9, in
print (d['c'])
KeyError: 'c'
在上面的示例中,字典中没有名为“c”的键弹出运行时错误。为了避免这种情况,并使用户意识到某个特定键不存在或在该位置弹出默认消息,有几种方法可以处理丢失的键。
方法 1:使用 get()
当我们必须检查密钥时,get(key,def_val)方法很有用。如果键存在,则打印与键关联的值,否则返回传入参数的 def_value。
例子:
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'))
输出:
0091
Not Found
方法 2:使用 setdefault()
setdefault(key, def_value)的工作方式与 get() 类似,但不同之处在于每次缺少键时,都会使用与传入参数的键关联的 def_value 创建一个新键。
例子:
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'])
输出:
0091
Not Present
方法3:使用defaultdict
“ defaultdict ”是一个在名为“ collections ”的模块中定义的容器。它接受一个函数(默认工厂)作为它的参数。默认情况下,默认工厂设置为“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 : 1
The value associated with 'c' is : Key Not found