pythonconfigparser

How to initialize ConfigParser with structured dict?


I want to initialize configparser with structured dict like:

from configparser import ConfigParser
from sys import stdout

structured_dict = dict(section1=dict(option1=1, option2=2, option3=3))
config = ConfigParser(structured_dict)
config.write(stdout)
# my expected result:
# [section1]
# option1=1
# option2=2
# option3=3
# ... but nothing to show

Environment


Solution

  • I found a useful method called 'read_dict' that solved the problem.

    from configparser import ConfigParser
    from sys import stdout
    
    structured_dict = dict(section1=dict(option1=1, option2=2, option3=3))
    config = ConfigParser()
    config.read_dict(structured_dict)
    config.write(stdout)
    
    # It writes this result in stdout as I expected:
    # [section1]
    # option1 = 1
    # option2 = 2
    # option3 = 3