Convert ConfigParser.items('') to dictionary

后端 未结 9 1089
再見小時候
再見小時候 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:40

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

    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
    

提交回复
热议问题