Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store dictionary and list in python config file?

Tags:

python

config

I'm using config.ini file to store all my configurations.

I need to store a dictionary and a list in the config file and parse it in my main.py file using configparser. Can anyone please tell me how do I go about doing that?

config.ini:

[DEFAULT] 
ADMIN = xyz 
SOMEDICT = {'v1': 'k1', 'v2': 'k2'}
SOMELIST = [v1, v2]

main.py:

config = configparser.ConfigParser() 
config.read('config.ini') 
secret_key = config['DEFAULT']['ADMIN']

If there is no way to do this, is config in json format a good option?

like image 811
90abyss Avatar asked Aug 29 '17 21:08

90abyss


1 Answers

ConfigParser will only ever give you those elements as strings, which you would then need to parse.

As an alternative, YAML is a good choice for configuration files, since it is easily human readable. Your file could look like this:

DEFAULT:
    ADMIN: xyz
    SOMEDICT:
        v1: k1
        v2: k2
    SOMELIST:
        - v1
        - v2

and the Python code would be:

import yaml
with open('config.yml') as c:
    config = yaml.load(c)
config['DEFAULT']['SOMEDICT']
like image 144
Daniel Roseman Avatar answered Oct 16 '22 08:10

Daniel Roseman