Back to practice

Repair a missing-field crash

Difficulty: Easy

Python

Try your first run

No account is needed to try this exercise. Write your answer, run the tests, and use the feedback to improve it.

  1. Read the examples and the required return value.
  2. Edit the supplied function in the editor, keeping its name and parameters. Return your answer, then select Run code.
  3. Use the test feedback to try again. Hints are available without replacing your code.

Sign in to save items for review and keep private notes.

Repair solve(record) so it returns the value stored under the dictionary key "name" when that key exists. If the key is absent, return "unknown". A present name is always a string and may be empty. Do not change the dictionary.

Understand the failure

The starter indexes the dictionary directly. That works for a record containing a name but raises KeyError for {}. A useful repair must handle absence while preserving valid values; it must not substitute the fallback merely because a value is falsey.

Work through an example

{"name": "Ada"} returns "Ada". {"role": "student"} returns "unknown" because there is no name key. {"name": ""} returns the empty string, not the fallback: the key exists even though its value has length zero.

Edge cases to check

  • The dictionary can be empty.
  • A present name can be an empty string or contain only spaces.
  • Other keys must be ignored and preserved.
  • Case matters: "Name" is a different key from "name".

Python details

Use dictionary-key semantics, not attribute access such as record.name. Empty strings are falsey in Python, so checking truthiness is different from checking presence. Do not trim or otherwise rewrite a supplied name.

Regression task

Run the starter on {} and record the exception. Keep both the missing-key and empty-string cases when checking your repair; one alone cannot prove the distinction is correct.

Examples

{}'unknown'
{'name': ''}''
{'name': 'Ada'}'Ada'

Constraints

Inputs are JSON-compatible. Unless a tighter bound is stated, lists have at most 200 elements, strings at most 1000 characters, and integers are within -1000000..1000000. Do not mutate inputs. Use only the browser runner; no file or network access. Preserve the required function signature.

Review lesson: Read errors before changing code
Python

Ready when you are

Write your solution, then run it against the practice tests.

Press Esc, then Tab to leave the editor. Code runs in an isolated browser workspace. Tests support learning, not verified grading.

Reset your code?

This replaces your current code with the starter and stops any running tests.