所以我有一个方法,它将字典对象作为参数。我想查看字典以确保它具有所有正确的密钥,如果没有抛出自定义异常。到目前为止我的代码有效,但我想可能有更好的方法。 (使用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)
链接到Python小提琴Link
答案 0 :(得分:4)
循环可以提供帮助:
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))
答案 1 :(得分:2)
如何在元组中编写要检查的所有键?
def mymethod(temp_dict):
mykeys = ('key1', 'key2', 'key3', ..., 'keyN')
for k in mykeys:
if k not in temp_dict:
raise CustomException("{} missing from dictionary".format(k))
这样,只要你想添加一个新密钥来检查,你就可以将它添加到元组而不是复制代码。
答案 2 :(得分:1)
一种可能性是使用诸如voluptuous之类的模式库,您可以在其中定义字典模式,通过定义哪些密钥是必需的,哪些是可选的,甚至是键可以接受的类型。
另一方面,如果你只需要验证是否存在所有必需的键,我就会使用这个很棒的小功能。首先,我们定义一个包含所有必需键的列表。然后我们使用all
方法检查给定字典是否包含所有这些必需的键。
def validate_params(params, req_keys=[]):
"""
Verify if all required keys are present in the dictionary passed
to this method
:param params: Parameter Dictionary to check
:param req_keys: These Keys are required in the dictionary
:rtype: Boolean
:returns: True or False
"""
if all(_ in params for _ in req_keys):
return True
raise CustomException("Not all keys present in dictionary")
我在pythonfiddle.com上添加了一个小提琴。
答案 3 :(得分:0)
使用any
功能:
if any(k not in temp_dict for k in ('key', 'key1', 'key2', 'key3')):
raise CustomException("Some keys are missing from dict")
答案 4 :(得分:0)
执行此操作的最Pythonic方法是使用循环:
>>> class CustomException(Exception):
... pass
...
>>> keys = 'key0 key1 key2 key3'.split()
>>> my_dict = {k: v for k, v in zip(keys, xrange(4))}
>>>
>>> for k in keys:
... if not k in my_dict:
... raise CustomException('Key %s not in dictionary.' % k)
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
__main__.CustomException: Key key4 not in dictionary.
>>>
然而,更加Pythonic的方法是让你的函数在你使用函数时为函数中的每个必需键做一个try/except
。例如:
>>> keys = 'key0 key1 key2 key3 key4'.split()
>>>
>>> def f(my_dict):
... for key in keys:
... try:
... print k, my_dict[k]
... except KeyError:
... raise CustomException('Key %s not in dictionary.' % k)
...
>>> my_dict = {k: v for k, v in zip(keys[:-1], xrange(len(keys) - 1))}
>>> assert my_dict == {'key0': 0, 'key1': 1, 'key2': 2, 'key3': 3} # Note no 'key4'
>>> f(my_dict)
key4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in f
__main__.CustomException: Key key4 not in dictionary.
>>>
这被称为“比宽容更容易获得宽恕”(或“EAFP”)原则。继续你打算做什么,直到某些事情阻止你。