让我的字典成为
dict1={1:'one',2:'two',3:'three',4:'four'}
如果我试图找到不在字典中的key值,例如
dict1[5]
它会给您一个错误,但是有什么办法可以使我没有收到错误,并且可以为字典中没有的每个键都获取特定的值,例如'none'或'not found']
dict1[5] # raises KeyError
dict1.get(5) # returns None
dict1.get(5, "not found") # returns "not found"
dict1.get(<key>, <value if missing, default: None>)