Read a Settings File
Advanced · Stretch · from Python Try-Except: Handle Errors Without Crashing
From the lesson: Python Try-Except: Handle Errors Without Crashing
Imagine a trapeze artist performing high above the ground. No matter how skilled they are, there's always a safety net below. If they slip, the net catches them and they can climb back up and try again.
Read the lessonWrite a function parse_settings(lines) that reads the lines of a settings file and returns a dictionary.
parse_settings(["# server", "port = 8080", "ratio=0.25", "debug = TRUE", "name = api"])
# {'port': 8080, 'ratio': 0.25, 'debug': True, 'name': 'api'}The rules:
#.key = value. Split it at the first = and remove the spaces around the key and the value.int if it can, otherwise a float if it can, otherwise True or False for "true" or "false" in any mix of capitals, otherwise it stays text.ValueError with the message duplicate key: followed by the key.Use try and except to find out whether a value is a number. Some of the tests are hidden.
def parse_settings(lines):
pass
Solution unlocks after your first Check
What Check runs
Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| parse_settings(["port = 8080", "debug=true"]) | {'port': 8080, 'debug': True} |
| parse_settings(["# server", "", "ratio = 0.25", "name = api"]) | {'ratio': 0.25, 'name': 'api'} |
More Try-Except exercises
- Safe DivisionBeginner
- Predict the OutputBeginner
- Fix the Number ConverterIntermediate
- Input Validator with raiseIntermediate
- Safe Dictionary LookupAdvanced
- Build a Safe CalculatorAdvanced
All Python exercises · 50 practice problems · Error Handling quiz