'Validating each values in dictionary or throw exception
How I can validate data type of each value of the following dictionary or throw exception dict = {"A":"some_string", "B":12, "C":83, "D":True}
I have to validate such that if key is A then value should be string and if key is B then value should be int, C then value should be int and if key is D value should be boolean. so based on key, validation for values also varies...
And if these conditions are not satisfying we must get an exception and program execution must stop
How can I do this?
Solution 1:[1]
In general, you can use use raise to raise an exception like this, and the type of exception that makes sense here is a TypeError.
When there are a number of requirements like this, you can store them in a dict to make things more readable:
test_dict = {'A': 'some_string': 'B': 12, 'C': 83, 'D': True}
required_types = {'A': str, 'B': int, 'C': int, 'D': bool}
for key, value in test_dict.items():
if key in required_types and not isinstance(value, required_types[key]):
raise TypeError(value)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pi Marillion |
