0

Whats the best way to validate each values in dictionary with out using any external libraries

for example dict = {"A":"some_string",
                    "B":12,
                    "C":83,
                    "D":56.......so on}

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 and ranges from 1 to 20 if key is C then value should be int and ranges from 1 to 100 so based on key, validation for values also varies...

any shorter way to do it ? my dictionary size is huge

3
  • 2
    How many keys are there? And do you have any pattern between corresponding value requirements?
    – niyasc
    Mar 23, 2016 at 6:08
  • 1
    From where did these rules originate? Without that, it's not a very well defined question.
    – Ami Tavory
    Mar 23, 2016 at 6:08
  • 2
    create another dictionary with key mapped to validation functions and use something like validations[key](value)
    – Bahrom
    Mar 23, 2016 at 6:08

2 Answers 2

8

Here's an approach with another dictionary:

d = {"A":"some_string",
     "B":12,
     "C":83,
     "D":56}

# Map your validation functions to the keys
validations = {
    "A": lambda x: isinstance(x, str),
    "B": lambda x: isinstance(x, int) and 1 <= x <= 20,
    "C": lambda x: isinstance(x, int) and 1 <= x <= 100,
}

for k, v in d.items():
    print(validations.get(k, lambda x: False)(v))  # Default validation just returns False (invalid)

To check whether the dictionary is valid, you could use:

print(all(validations.get(k, lambda x: False)(v) for (k, v) in d.items()))
0

Let's say that you define the expected types in a dictionary:

typeExpected = {'A':str, 'B':int}

meaning that key A should contain a string and key B should contain a int. Let's define the dictionary you want to test as:

exampleData = {'A':'ok', 'B':0}

Now you can verify correctness of the types by running:

map(lambda x: type(exampleData[x]) == typeExpected[x], exampleData)

Try this on your data and if your dictionary is indeed too big, it would be easy to transform the map into a pool.map to work in multiprocessing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.