Convert ConfigParser.items('') to dictionary

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

    Another alternative would be:

    config.ini

    [DEFAULT]
    potato=3
    
    [foo]
    foor_property=y
    potato=4
    
    
    [bar]
    bar_property=y
    

    parser.py

    import configparser
    from typing import Dict
    
    
    def to_dict(config: configparser.ConfigParser) -> Dict[str, Dict[str, str]]:
        """
        function converts a ConfigParser structure into a nested dict
        Each section name is a first level key in the the dict, and the key values of the section
        becomes the dict in the second level
        {
            'section_name': {
                'key': 'value'
            }
        }
        :param config:  the ConfigParser with the file already loaded
        :return: a nested dict
        """
        return {section_name: dict(config[section_name]) for section_name in config.sections()}
    

    main.py

    import configparser
    
    from parser import to_dict
    
    
    def main():
        config = configparser.ConfigParser()
        # By default section names are parsed to lower case, optionxform = str sets to no conversion.
        # For more information: https://docs.python.org/3/library/configparser.html#configparser-objects
        # config.optionxform = str
        config.read('config.ini')
        print(f'Config read: {to_dict(config)}')
        print(f'Defaults read: {config.defaults()}')
    
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题