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()
config.read('conf.ini')
connection_string = ("dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' "
"password='%(password)s' port='%(port)s'")
print connection_string % config.items('db')
This is actually already done for you in
config._sections. Example:And then:
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(), becauseconfig._sectionsis provided by the module for you already.Example test.ini:
Magic happening:
So this solution is not wrong, and it actually requires one less step. Thanks for stopping by!