TAGS :Viewed: 5 - Published at: a few seconds ago

[ Convert ConfigParser.items('') to dictionary ]

How can I convert the result of a ConfigParser.items('section') to a dictionary to format a string like here:

import ConfigParser

config = ConfigParser.ConfigParser()

connection_string = ("dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' "
                     "password='%(password)s' port='%(port)s'")

print connection_string % config.items('db')

Answer 1

Have you tried

print connection_string % dict(config.items('db'))


Answer 2

This is actually already done for you in config._sections. Example:

$ cat test.ini
[First Section]
var = value
key = item

[Second Section]
othervar = othervalue
otherkey = otheritem

And then:

>>> from ConfigParser import ConfigParser
>>> config = ConfigParser()
>>> config.read('test.ini')
>>> config._sections
{'First Section': {'var': 'value', '__name__': 'First Section', 'key': 'item'}, 'Second Section': {'__name__': 'Second Section', 'otherkey': 'otheritem', 'othervar': 'othervalue'}}
>>> config._sections['First Section']
{'var': 'value', '__name__': 'First Section', 'key': 'item'}

Edit: My solution to the same problem was downvoted so I'll further illustrate how my answer does the same thing without having to pass the section thru dict(), because config._sections is provided by the module for you already.

Example test.ini:

dbname = testdb
dbuser = test_user
host   = localhost
password = abc123
port   = 3306

Magic happening:

>>> config.read('test.ini')
>>> config._sections
{'db': {'dbname': 'testdb', 'host': 'localhost', 'dbuser': 'test_user', '__name__': 'db', 'password': 'abc123', 'port': '3306'}}
>>> connection_string = "dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' password='%(password)s' port='%(port)s'"
>>> connection_string % config._sections['db']
"dbname='testdb' user='test_user' host='localhost' password='abc123' port='3306'"

So this solution is not wrong, and it actually requires one less step. Thanks for stopping by!

Answer 3

How I did it in just one line.

my_config_parser_dict = {s:dict(config.items(s)) for s in config.sections()}

No more than other answers but when it is not the real businesses of your method and you need it just in one place use less lines and take the power of dict compression could be useful.

Answer 4

I know this was asked a long time ago and a solution chosen, but the solution selected does not take into account defaults and variable substitution. Since it's the first hit when searching for creating dicts from parsers, thought I'd post my solution which does include default and variable substitutions by using ConfigParser.items().

from ConfigParser import SafeConfigParser
defaults = {'kone': 'oneval', 'ktwo': 'twoval'}
parser = SafeConfigParser(defaults=defaults)
parser.set('section1', 'kone', 'new-val-one')
parser.set('section1', 'kone', 'new-val-one')
parser.get('section1', 'ktwo')
parser.get('section2', 'kone')
parser.set('section2', 'kthree', 'threeval')
thedict = {}
for section in parser.sections():
    thedict[section] = {}
    for key, val in parser.items(section):
        thedict[section][key] = val
{'section2': {'ktwo': 'twoval', 'kthree': 'threeval', 'kone': 'oneval'}, 'section1': {'ktwo': 'twoval', 'kone': 'new-val-one'}}

A convenience function to do this might look something like:

def as_dict(config):
    Converts a ConfigParser object into a dictionary.

    The resulting dictionary has sections as keys which point to a dict of the
    sections options as key => value pairs.
    the_dict = {}
    for section in config.sections():
        the_dict[section] = {}
        for key, val in config.items(section):
            the_dict[section][key] = val
    return the_dict

Answer 5

For an individual section, e.g. "general", you can do: