Editor

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 lesson

Write 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:

  • Skip blank lines and lines whose first character after any spaces is #.
  • Every other line holds key = value. Split it at the first = and remove the spaces around the key and the value.
  • The value becomes an 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.
  • If a key appears twice, raise 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.

    RunsExpected 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

    All Python exercises · 50 practice problems · Error Handling quiz