0

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?

  • Does this answer your question? [How to validate structure (or schema) of dictionary in Python?](https://stackoverflow.com/questions/45812387/how-to-validate-structure-or-schema-of-dictionary-in-python) – Jack Taylor Apr 25 '22 at 04:58
  • Hi Jack, Appreciate your response. I don't have any config schema. I just need to validate the dictionary and throw exception if the condition are not satisfied. – MikeW14 Apr 25 '22 at 05:05

1 Answers1

3

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)
Pi Marillion
  • 4,465
  • 1
  • 19
  • 20