Convert ConfigParser.items('') to dictionary

后端 未结 9 1101
再見小時候
再見小時候 2020-12-12 18:44

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

import ConfigParser

config = ConfigParser.Co         


        
9条回答
  •  没有蜡笔的小新
    2020-12-12 19:28

    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:

    [db]
    dbname = testdb
    dbuser = test_user
    host   = localhost
    password = abc123
    port   = 3306
    

    Magic happening:

    >>> config.read('test.ini')
    ['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!

提交回复
热议问题