You receive a list of contacts where each item looks like one of these:
raw = [
" Alice Smith,alice@example.com,42 ",
"Bob Brown,BOB@EXAMPLE.com,", # missing age
"carol,wrong-email,29", # no last name, bad email
",dave@example.com,55", # no name
" Eve Wells, EVE@example.com , 31 ",
]
You want a clean list of dicts with valid contacts only.
cleaned = []
for line in raw:
parts = [p.strip() for p in line.split(",")]
cleaned.append(parts)
contacts = []
for name, email, age_text in cleaned:
if not name: continue # need a name
if "@" not in email: continue # need an @
try:
age = int(age_text)
except ValueError:
age = None
contacts.append({
"name": name.title(),
"email": email.lower(),
"age": age,
})
for c in contacts:
print(c)
Output:
{'name': 'Alice Smith', 'email': 'alice@example.com', 'age': 42}
{'name': 'Bob Brown', 'email': 'bob@example.com', 'age': None}
{'name': 'Eve Wells', 'email': 'eve@example.com', 'age': 31}
Carol got dropped (bad email) and Dave got dropped (no name). Bob made it in with a None age. Real data, real result.
continue) and "guess if we can" (try/except).Extend the cleaner: also reject contacts under age 18. Add a counter for how many were rejected and print it at the end.