发生异常时如何抛出异常检索项不在列表或di中

2024-09-28 01:30:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读一个文件,把内容放进字典里。我正在编写一个方法,在其中搜索键并返回其值。如果我的键不在字典中,如何抛出异常。例如,下面是我正在测试的代码,但是我得到了检索对于不匹配项为“无”。 我可以使用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")

找到 找不到


Tags: 文件方法key代码内容apple字典has
3条回答

Python倾向于“请求原谅比允许更容易”的模式,而不是“三思而后行”。因此,在您的代码中,在尝试提取它的值之前,不要搜索键,只需提取它的值并根据需要(以及在需要的地方)处理余波。你知道吗

*假设您询问如何找到一个键,并返回它的值。你知道吗

EAFP方法:

def some_func(key)
    my_dict = {'fruit':'apple', 'vegi':'carrot'}
    return my_dict[key]   # Raises KeyError if key is not in my_dict

如果你要做的是LBYP,试试这个:

def some_func(key):
    my_dict = {'fruit':'apple', 'vegi':'carrot'}
    if not key in my_dict:
        raise SomeException('my useful exceptions message')
    else:
        return my_dict[key]

LBYP方法的最大问题是它引入了一个竞争条件;“key”可能存在,也可能不存在,在检查它,然后返回它的值之间(只有在执行当前工作时才可能存在)。你知道吗

你可以简单地用in。你知道吗

mylist = {'fruit':'apple','vegi':'carrot'}

test = ['fruit', 'vegi', 'veg']
for value in test:
    if value in mylist:
        print(value + ' is in the dict, its value : ' + mylist[value])
    else:
        raise Exception(value + ' not in dict.')

# Console
# fruit is in the dict, its value: apple
# vegi is in the dict, its value: carrot
# Exception: veg is not in dict

@JRazor为您提供了几种使用列表理解、lambda和filter的方法来实现您所称的“has\u key()方法”(不过,当我将它们复制/粘贴到python2.7解释器时,我得到了SyntaxError)你知道吗

下面是您的问题的字面答案:“如果字典中没有我的键,如何抛出异常?”

许多语言称之为throw(异常),python调用raise(异常)。 更多关于here的信息。你知道吗

在本例中,可以添加如下自定义异常:

mylist = {'fruit':'apple','vegi':'carrot'} # mylist is a dictionary. Just sayin'

if "key" not in mylist:
    raise Exception("Key not found")
else:
    print "Key found"

相关问题 更多 >

    热门问题