我正在读一个文件,把内容放进字典里。我正在编写一个方法,在其中搜索键并返回其值。如果我的键不在字典中,如何抛出异常。例如,下面是我正在测试的代码,但是我得到了检索对于不匹配项为“无”。 我可以使用has\u key()方法吗?你知道吗
mylist = {'fruit':'apple','vegi':'carrot'}
for key,value in mylist.items():
found = re.search('vegi',key)
if found is None:
print("Not found")
else:
print("Found")
找到 找不到
Python倾向于“请求原谅比允许更容易”的模式,而不是“三思而后行”。因此,在您的代码中,在尝试提取它的值之前,不要搜索键,只需提取它的值并根据需要(以及在需要的地方)处理余波。你知道吗
*假设您询问如何找到一个键,并返回它的值。你知道吗
EAFP方法:
如果你要做的是LBYP,试试这个:
LBYP方法的最大问题是它引入了一个竞争条件;“key”可能存在,也可能不存在,在检查它,然后返回它的值之间(只有在执行当前工作时才可能存在)。你知道吗
你可以简单地用in。你知道吗
@JRazor为您提供了几种使用列表理解、lambda和filter的方法来实现您所称的“has\u key()方法”(不过,当我将它们复制/粘贴到python2.7解释器时,我得到了
SyntaxError
)你知道吗下面是您的问题的字面答案:“如果字典中没有我的键,如何抛出异常?”
许多语言称之为
throw
(异常),python调用raise
(异常)。 更多关于here的信息。你知道吗在本例中,可以添加如下自定义异常:
相关问题 更多 >
编程相关推荐