Home > Software design >  Validate dictionary values
Validate dictionary values

Time:11-02

I'm trying to create a function that receives any argument but only returns True if it's a dictionary. Until here, it's ok. But my dic has some rules: haver 3 keys: 'name', 'pass' and 'rule'. 'name' & 'pass' values should né strings and have more than 1 word. 'rule' value is a dic with 2 keys: ' vals' which is a tuple with 2 positive integers & 'char' is a single lowercase letter.

Should be something like:

IsValid({'name':john.d', 'pass':'aabcde', 'rule':{'vals':(2,4), 'char':'a'}})

True

IsValid({'name':john.d', 'pass':'aabcde', 'rule':{'vals':1, 'char':'a'}})

False

How can I access to every single Key and make a condition for every field of the value?

CodePudding user response:

You could try something like this:

def IsValid (data):
    if type(data) is not dict:
        return False

    if 'name' not in data:
        return False
    elif type(data['name']) is not str:
        return False

    # add the remaining checks
    # ......

    # All ok, return True
     return True

CodePudding user response:

Basically have the function check all of those.

like :

  def my_checker_function(unsafe_dict):
    for key in ['name', 'pass', 'rule']:
      if key not in unsafe_dict:
        return False
    if not isinstance(unsafe_dict['name'], str): 
      return False
    # more checks
    return True

Just write your exceptions this way, returning False. And at the very end, return True.

CodePudding user response:

def isValid(a):
    keys = ['name', 'pass', 'rule']
    if isinstance(a, dict) and all([i in a for i in keys]):
        if all([isinstance(a[i], str) for i in keys[:-1]]):
            if isinstance(a['rule'], dict) and all([i in a['rule'] for i in ['vals', 'char']]):
                if isinstance(a['rule']['vals'], tuple) and len(a['rule']['char']) == 1 and a['rule']['char'].islower():
                    return True
    return False
  • Related