Editor

Read an INI Config File

#144 · Parsing · Advanced · 130 XP · about 25 min

Many programs keep their settings in INI files: plain text split into sections. Write parse_config(text) that reads such text and returns a dictionary that maps each section name to a dictionary of its settings.

  • A line [name] starts a section, and spaces around the name inside the brackets are ignored. Settings before the first section belong to a section called 'global', which is left out if it has no settings.
  • A setting line looks like key = value and is split at its first =. Spaces around the key and the value are removed, and keys are lowercased. If a key appears again in the same section, the later value replaces the earlier one.
  • Blank lines, and lines whose first non-space character is # or ;, are ignored. A # later in a line is part of the value.
  • If a section name appears again, its settings are added to the existing section.
  • Values are converted: a whole number such as 8080 or -7 becomes an int, true and false in any case become True and False, and a value wrapped in double quotes becomes the text inside the quotes, unconverted. Everything else stays a string.
  • Sections and keys keep the order in which they first appear.

Examples

text = """
# demo settings
name = Demo App
[server]
host = 0.0.0.0
port = 8080
debug = TRUE
[paths]
home = "/srv/demo"
"""
parse_config(text)
# returns {'global': {'name': 'Demo App'},
#          'server': {'host': '0.0.0.0', 'port': 8080, 'debug': True},
#          'paths': {'home': '/srv/demo'}}
parse_config('code = "007"\nretries = 3')
# returns {'global': {'code': '007', 'retries': 3}}

Constraints

  • text has 0 to 10,000 characters.
  • Every line that is not blank, a comment or a section header contains an = with a non-empty key before it.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.