3
[section 1]
key1:value1
key2:value2

[section 2]
key1:value1
key2:value2

I have tried to parse this config file into dictionary using python but i was unable to do

This is my code:

import configparser
config = configparser.ConfigParser
filename = '/home/Documents/dictionary parsing/config.cfg'

def read_config_file(filename):
    with open(file=filename, mode='r') as fs:
        return{k.strip(): v.strip() for i in [l for l in fs.readlines() if l.strip() != ''] for k, v in [i.split('=')]}

print('dictionary: ',read_config_file(filename))
2
  • 2
    Where is your attempt? Commented May 27, 2022 at 10:09
  • 2
    you should give a look to configparser the documentation is quite clear and cover your use case Commented May 27, 2022 at 10:10

1 Answer 1

3

This is the way:

import configparser
config = configparser.ConfigParser()
# The name of your file
config.read('example.ini')

dictionary = {}
for section in config.sections():
    dictionary[section] = {}
    for option in config.options(section):
        dictionary[section][option] = config.get(section, option)

print(dictionary)
        

The sections method return a list of all the sections in your config file, the options method returns all of the options for a section. Using the get method of the configparser library you can access all the section-option combo you have loaded from you config file and then place them in a dict with the same schema.

Sign up to request clarification or add additional context in comments.

1 Comment

A shorthand for the dictionary creation would be dictionary = {section: dict(config[section].items()) for section in config.sections()}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.