type of data
<class 'collections.OrderedDict'>
if("a" not in data or "b" not in data or "c" not in data or
"d" not in data or "e" not in data or "f" not in data or
"g" not in data or "h" not in data or "i" not in data):
raise serializers.ValidationError("All Required Parameters not provided")
i am checking for all these parameters whether they are present in my ordered dictionary or not is there any better way to check this?
CodePudding user response:
You can do this,
if any(i not in data for i in list('abcdefghijkli')):
raise serializers.ValidationError("All Required Parameters not provided")
list('abcdefghijkli')
-> ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'i']
. You can also use the entire list if you set of keys to check. like this,
if any(i not in data for i in ['key_1', 'key_2'. 'key_3']):
raise serializers.ValidationError("All Required Parameters not provided")
Execution:
In [1]: d
Out[1]: defaultdict(None, {'1': None, '2': None, 'c': None})
In [2]: any(i not in data for i in list('abcdefghijkli'))
Out[2]: True
CodePudding user response:
You can use set
s to determine membership:
def has_required_keys(data, required_keys):
return len(set(data.keys()) & set(required_keys)) == len(required_keys)