+1 vote
in Programming Languages by (35.2k points)

I want to read a ".ini" configuration file and create a dictionary using the content of the file.

E.g., my configuration file has the following data. I want to create two dictionaries - one using param1 and another using param2. Is there any Python library to parse such a configuration file?

[param1]

apple=12

mango=23

orange=34

grape=45

[param2]

fish=123

chicken=423

rice=54

1 Answer

+4 votes
by (45.3k points)
selected by
 
Best answer

You can use the configparser module to parse the ".ini" configuration file. I created a "temp.ini" file using the above content.

Here is the code that converts the content into the dictionary.

>>> import configparser

>>> config = configparser.ConfigParser()

>>> config.read('temp.ini')

['temp.ini']

>>> config['param1']

<Section: param1>

>>> dict1= dict(config['param1'])

>>> dict1

{'apple': '12', 'mango': '23', 'orange': '34', 'grape': '45'}

>>> dict2= dict(config['param2'])

>>> dict2

{'fish': '123', 'chicken': '423', 'rice': '54'}

>>> 


...