config file with a dictionary using python

Jesse Dugger picture Jesse Dugger · Jul 3, 2016 · Viewed 22.8k times · Source

So I am trying to use a dictionary inside a config file to store a report name to an API call. So something like this:

report = {'/report1': '/https://apicall...', '/report2': '/https://apicall...'}

I need to store multiple reports:apicalls to one config value. I am using ConfigObj. I have read there documentation, documentation and it says I should be able to do it. My code looks something like this:

from configobj import ConfigObj
config = ConfigObj('settings.ini', unrepr=True)
for x in config['report']:
    # do something... 
    print x

However when it hits the config= it throws a raise error. I am kinda lost here. I even copied and pasted their example and same thing, "raise error". I am using python27 and have the configobj library installed.

Answer

Mary Marchini picture Mary Marchini · Jul 3, 2016

If you're not obligated to use INI files, you might consider using another file format more suitable to handle dict-like objects. Looking at the example file you gave, you could use JSON files, Python has a built-in module to handle it.

Example:

JSON File "settings.json":

{"report": {"/report1": "/https://apicall...", "/report2": "/https://apicall..."}}

Python code:

import json

with open("settings.json") as jsonfile:
    # `json.loads` parses a string in json format
    reports_dict = json.load(jsonfile)
    for report in reports_dict['report']:
        # Will print the dictionary keys
        # '/report1', '/report2'
        print report