Home > Mobile >  Python, find all missing fields in a dictionary
Python, find all missing fields in a dictionary

Time:10-05

I wrote a function that validates if all the fields exist in a python dictionary. Below is the code.

def validate_participants(self, xml_line):
    try:
       participant_type = xml_line["participants"]["participant_type"]
       participant_role = xml_line["participants"]["participant_role"]
       participant_type = xml_line["participants"]["participant_type"]
       participant_id   = xml_line["participants"]["participant_id"]
       return True
     except KeyError as err:
       log.error(f'{err}')
       return False

This raises an error about the missing key that it finds first and breaks execution. I want to go through the entire set of fields and raise error with all the missing fields. What's the best/efficient way to solve the problem?

CodePudding user response:

Using a set you can get the difference and if it is empty the keys are not missing.

def validate_participants(self, xml_line):
    keys = {"participant_type", "participant_role", "participant_id"}
    return keys - xml_line["participants"].keys() or True

The or True means return the set of missing keys if there are missing keys otherwise return True

Edit:

To answer your comment there is no need to use a try/except if you check first:

def validate_participants(self, xml_line):
    keys = {"participant_type", "participant_role", "participant_id"}
    missing_keys = keys - xml_line["participants"].keys()

    if missing_keys:
        #return False or
        raise Value_Error(f"Missing values: {', '.join(missing_keys)}")

    #access the values/do work or
    return True

CodePudding user response:

I would define a set of the expected keys and subtract the actual keys:

expected_keys = {...}
actual_keys = xml_line["participants"].keys()
key_diff = expected_keys - actual_keys

Now create a message from key_diff about which keys are missing.

  • Related