简体   繁体   中英

Typecast dictionary values obtained via ConfigParser

I am using ConfigParser to get a large number of variables that are set in a configuration file, CONFIG.txt.

import ConfigParser
parser = ConfigParser.ConfigParser()
parser.read('CONFIG.txt')
settings = dict(parser.items('some_section'))

I actually create several dictionaries from the different config file sections and have stored them in a nested format. I want to keep the variables stored in dictionary format as it makes it easy to pass around many at a time to various functions. ConfigParser stores all the text from the file as strings. Is there a quick way to typecast the variables properly. Some of the variables are lists of strings, some strings, some integers and some floats. I can format the config file how I like and don't even really need to use ConfigParser if someone can suggest a more suitable alternative.

Thanks.

Given that you can use whatever format you like, I'd say the simplest approach is JSON:

$ cat a.json
{
  "categ": {
    "one": 0.3,
    "two": 123,
    "three": "hello",
    "four": true
  },
  "other": [1, 2, 3]
}
$ python -c 'import json; print json.load(open("a.json"))'
{u'categ': {u'four': True, u'three': u'hello', u'two': 123, u'one': 0.3}, u'other': [1, 2, 3]}

You get arbitrary nested and basic types for free, and very easy loading using the json module.

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