简体   繁体   中英

How to store dictionary and list in python config file?

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?

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']

I would suggest to use json :

json.loads('[1, 2]') #=> [1, 2]
json.dumps([1, 2]) #=> '[1, 2]'
json.loads('{"v1": "k1", "v2": "k2"}') #=> {'v1': 'k1', 'v2': 'k2'}
json.dumps({'v1': 'k1', 'v2': 'k2'}) #=> '{"v1": "k1", "v2": "k2"}'

You will need to do dumps before saving and loads after reading for those fields you use JSON for.

Better solution would be to use JSON for the entire configuration file:

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

Then you could do:

conf = json.load(open('conf.json'))
json.dump(conf, open('conf.json', 'w'))

A JSON file with this data could look like this:

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

Then in python:

import json

with open('config.json') as f:
    config = json.load(f)

It is possible to store and read Dict or List data from an ini file

after reading the value you just have to use the built in eval( ) function, by default the variable will be of type string eval will check and convert it to the dictionary data type.

You can try the following code

dict_data = configur.get("DEFAULT", "SOMEDICT")
dict_data = eval(dict_data)

print(dict_data['v1'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM