有没有办法将int或字符串分配给未在我的词典中指定为键的特定值?

问题描述 投票:0回答:1

让我的字典成为

      dict1={1:'one',2:'two',3:'three',4:'four'}

如果我试图找到不在字典中的key值,例如

       dict1[5]

它会给您一个错误,但是有什么办法可以使我没有收到错误,并且可以为字典中没有的每个键都获取特定的值,例如'none'或'not found']

python dictionary pycharm
1个回答
0
投票
dict1[5]                   # raises  KeyError
dict1.get(5)               # returns None
dict1.get(5, "not found")  # returns "not found"

Docs


0
投票

dict1.get(<key>, <value if missing, default: None>)

© www.soinside.com 2019 - 2024. All rights reserved.