代码之家  ›  专栏  ›  技术社区  ›  Szymon Lipiński

将configParser.items(“”)转换为字典

  •  54
  • Szymon Lipiński  · 技术社区  · 15 年前

    如何将configParser.items(“section”)的结果转换为字典以设置如下字符串的格式:

    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')
    
    6 回复  |  直到 6 年前
        1
  •  46
  •   jathanism    15 年前

    这实际上已经为你做了 config._sections . 例子:

    $ cat test.ini
    [First Section]
    var = value
    key = item
    
    [Second Section]
    othervar = othervalue
    otherkey = otheritem
    

    然后:

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

    编辑: 我对同一个问题的解决方案被否决了,因此我将进一步说明我的答案如何在不必通过该部分的情况下做同样的事情。 dict() ,因为 配置节 模块已经为您提供了 .

    test.ini示例:

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

    魔法发生:

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

    所以这个解决方案是 错了,实际上需要少走一步。谢谢您的光临!

        2
  •  90
  •   Ian Clelland    15 年前

    你试过了吗?

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

    ?

        3
  •  35
  •   martineau    6 年前

    我是如何做到这一点的。

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

    不比其他答案多,但当它不是你的方法的真正业务,你只需要在一个地方使用较少的行和采取的能力听写理解可能是有用的。

        4
  •  12
  •   James Kyle    11 年前

    我知道这是很久以前提出的,并且选择了一个解决方案,但是选择的解决方案没有考虑默认值和变量替换。因为这是搜索从解析器创建dict时的第一次点击,所以我想我会发布我的解决方案,其中包括使用configparser.items()进行默认和变量替换。

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

    执行此操作的便利功能可能类似于:

    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
    
        5
  •  2
  •   Keith Hughitt rjhcnf    10 年前

    对于单个部分,例如“常规”,您可以执行以下操作:

    dict(parser['general'])
    
        6
  •  0
  •   rbento    6 年前

    下面是另一种方法 Python 3.7 具有 configparser ast.literal_eval :

    游戏美

    [assets]
    tileset = {0:(32, 446, 48, 48), 
               1:(96, 446, 16, 48)}
    

    游戏

    import configparser
    from ast import literal_eval
    
    config = configparser.ConfigParser()
    config.read('game.ini')
    
    # convert a string to dict
    tileset = literal_eval(config['assets']['tileset'])
    
    print('tileset:', tileset)
    print('type(tileset):', type(tileset))
    

    输出

    tileset: {0: (32, 446, 48, 48), 1: (96, 446, 16, 48)}
    type(tileset): <class 'dict'>