Build a Medical Data Validator - Step 44

Tell us what’s happening:

for key in invalid_records:
print(f’Unexpected format “{key}: {val}” at position {index}.')
is_invalid = True
Why did my codes not pass? Please give me some advice. Thanks!

Your code so far

import re


medical_records = [
    {
        'patient_id': 'P1001',
        'age': 34,
        'gender': 'Female',
        'diagnosis': 'Hypertension',
        'medications': ['Lisinopril'],
        'last_visit_id': 'V2301',
    },
    {
        'patient_id': 'p1002',
        'age': 47,
        'gender': 'male',
        'diagnosis': 'Type 2 Diabetes',
        'medications': ['Metformin', 'Insulin'],
        'last_visit_id': 'v2302',
    },
    {
        'patient_id': 'P1003',
        'age': 29,
        'gender': 'female',
        'diagnosis': 'Asthma',
        'medications': ['Albuterol'],
        'last_visit_id': 'v2303',
    },
    {
        'patient_id': 'p1004',
        'age': 56,
        'gender': 'Male',
        'diagnosis': 'Chronic Back Pain',
        'medications': ['Ibuprofen', 'Physical Therapy'],
        'last_visit_id': 'V2304',
    }
]


def find_invalid_records(
    patient_id, age, gender, diagnosis, medications, last_visit_id
):

    constraints = {
        'patient_id': isinstance(patient_id, str)
        and re.fullmatch('p\d+', patient_id, re.IGNORECASE),
        'age': isinstance(age, int) and age >= 18,
        'gender': isinstance(gender, str) and gender.lower() in ('male', 'female'),
        'diagnosis': isinstance(diagnosis, str) or diagnosis is None,
        'medications': isinstance(medications, list)
        and all([isinstance(i, str) for i in medications]),
        'last_visit_id': isinstance(last_visit_id, str)
        and re.fullmatch('v\d+', last_visit_id, re.IGNORECASE)
    }

    return [key for key, value in constraints.items() if not value]


def validate(data):
    is_sequence = isinstance(data, (list, tuple))

    if not is_sequence:
        print('Invalid format: expected a list or tuple.')
        return False
        
    is_invalid = False
    key_set = set(
        ['patient_id', 'age', 'gender', 'diagnosis', 'medications', 'last_visit_id']
    )

    for index, dictionary in enumerate(data):
        if not isinstance(dictionary, dict):
            print(f'Invalid format: expected a dictionary at position {index}.')
            is_invalid = True
            continue

        if set(dictionary.keys()) != key_set:
            print(
                f'Invalid format: {dictionary} at position {index} has missing and/or invalid keys.'
            )
            is_invalid = True
            continue

        invalid_records = find_invalid_records(**dictionary)

# User Editable Region

        for key in invalid_records:
            print(f'Unexpected format "{key}: {val}" at position {index}.')        
            is_invalid = True

# User Editable Region

    if is_invalid:
        return False
    print('Valid format.')
    return True

validate(medical_records)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0

Challenge Information:

Build a Medical Data Validator - Step 44
https://www.freecodecamp.org/learn/full-stack-developer/workshop-medical-data-validator/step-44

the string you are printing has some differences from the required string

what differences do the codes have?

the quotes&ndsp; 

for (key,value),index in invalid_records:

        print(f'Unexpected format " {key} : {val} " at position {index}.')       

        is_invalid = True

Could you please give me a complete code so that I can know where is my different areas with the required string?

The requested string to print is Unexpected format '<key>: <val>' at position <index>., which uses single quotes, so you must also use single quotes

I was stuck on this one for a long team. Eventually I realized that it isn’t asking for the key val and index of the invalid_records lis that it is asking you to iterate over, it wants the key val and index of the parent dictionary. Good luck.

So what is correct code? please tell a little complete code that I can learn from that. Thanks very much!

it is not allowed to share code

you can share again the code you have now and people will keep helping you

you need to also keep in mind that you do not have variables key and val, those are placeholders, you need to use the actual variable names you have available

    for index in invalid_records:

        print(f"Unexpected format '{key}: {val}' at position {index}.")       

        is_invalid = True

where are key and val and index defined? are those variables that exist?

For the 1st line, in a key, value pair, what do you need to uniquely identify the record. You need to change only 1 word.

Before the print call to output the {value}, shouldn’t you extract it out from the dictionary using something unique?

Hope it helps.

# User Editable Region

    for key in invalid_records:
        print(f'Unexpected format "{key}: {dictionary\[key\]}" at position {index}.')        
        is_invalid = True

#Since we have to get the index from the outer loop, we can inherit and get the value of the key from the dictionary.

hi @tranvanthon

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge. How to Help Someone with Their Code Using the Socratic Method

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.