#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.
[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.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.# or ;, are ignored. A # later in a line is part of the value.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.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}}
text has 0 to 10,000 characters.= 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.