Python 检查字典对象是否有正确的键抛出自定义异常

bsc*_*ott 1 python dictionary python-2.7

所以我有一个以字典对象作为参数的方法。我想检查字典以确保它具有所有正确的键,如果没有则抛出自定义异常。到目前为止我的代码可以工作,但我认为可能有更好的方法。(使用Python 2.7)

def my_method(temp_dict):
    #this is the part that looks messy and I would like to improve
    if "key" not in temp_dict:
        raise CustomException("Message key is missing from dict")
    if "key1" not in temp_dict:
        raise CustomException("Message key1 is missing from dict")
    if "key2" not in temp_dict:
        raise CustomException("Message key2 is missing from dict")
    if "key3" not in temp_dict:
        raise CustomException("Message key3 is missing from dict")

my_dict = {}
my_dict["key"] = "test"
my_dict["key1"] = "test"
my_dict["key2"] = "test"

my_method(my_dict)
Run Code Online (Sandbox Code Playgroud)

链接到 Python Fiddle链接

Mik*_*ler 5

循环可以帮助:

def my_method(temp_dict):
    for key in ['key1', 'key2', 'key3']
        if key not in temp_dict:
            raise CustomException("Message {} is missing from dict".format(key))
Run Code Online (Sandbox Code Playgroud)