INI files are primarily used as a file format for configuration files. In this article, we will discuss how to convert a python dictionary to an INI file using the configparser module.
What is the INI File Format?
INI format, short for Initialization format, is a simple text file format used to store configuration settings for software applications. It was widely used in the early days of Windows and is still used in some applications today.
An INI file consists of sections, each of which contains key-value pairs. Each key-value pair is written as "key=value"
and is separated by an equals sign (=). Sections are enclosed in square brackets ([]
), and each key-value pair is written on a new line.
For example, consider the following INI file.
[employee]
name=John Doe
age=35
[job]
title=Software Engineer
department=IT
years_of_experience=10
[address]
street=123 Main St.
city=San Francisco
state=CA
zip=94102
The above data is an example of an INI file that contains information about an employee. The file is organized into three sections: [employee]
, [job]
, and [address]
.
- The
[employee]
section contains basic information about the employee, such as their name and age. [job]
section contains information about the employee’s job, including their job title, department, and years of experience.- The
[address]
section contains information about the employee’s address, including their street address, city, state, and zip code.
As you can see, INI files are easy to read and write by both humans and computers. This makes them a popular choice for storing configuration settings in many different types of software applications.
Nowadays, INI files aren’t much popular due to their inability to store nested or complex data. However, it is possible that you might need to store data from a python dictionary in an INI file for some purpose. Let us discuss how to convert a python dictionary to INI file format.
Convert Python Dictionary to INI File
We can convert a python dictionary to an INI file using the configparser module. However, we need to keep in mind that we can use nested dictionaries with one and only one nesting level. This is due to the reason that INI files cannot contain nested data.
We will use the following dictionary and convert it into an INI file.
{'employee': {'name': 'John Doe', 'age': '35'},
'job': {'title': 'Software Engineer', 'department': 'IT', 'years_of_experience': '10'},
'address': {'street': '123 Main St.', 'city': 'San Francisco', 'state': 'CA', 'zip': '94102'}}
The above dictionary contains three outer keys i.e. 'employee'
, 'job'
, and 'address'
. We will use these keys as sections in the INI file. Also, we will use the key-value pairs in the dictionaries associated with these keys as key-value pairs in the INI file for each section.
To convert the python dictionary to an INI file, we will use the following steps.
- First, we will create an empty
ConfigParser
object using theConfigParser()
function defined in the configparser module. - We will also open an INI file in write mode using the
open()
function. Theopen()
function takes the file name as its first argument and the python literal“w”
as the second argument. After execution, it returns a file pointer. - Next, we will add sections to the
ConfigParser
object. For this, we will use theadd_section()
method. Theadd_section()
method takes the section name as the input argument and adds it to theConfigParser
object. - To add the sections, we will first get the outer keys of the dictionary using the
keys()
method. Thekeys()
method, when invoked on the dictionary, returns a list of keys. We will iterate over the list of keys and add them as sections in theConfigParser
object. - After adding sections, we need to add fields for each section. For this, we will use the
set()
method. Theset()
method, when invoked on aConfigParser
object, takes three input arguments. The first argument is the section name, the second argument is the field name, and the third input argument is the field value. After execution, it adds the field to the corresponding section in theConfigParser
object. - To add the field names to the
ConfigParser
object, we will use the outer keys in the dictionary to access the inner dictionaries and iterate through the key-value pairs. For each section, we will iterate through the key-value pairs in the inner dictionary and add them to theConfigParser
object using theset()
method. - By now, we have added all the data from the dictionary to the
ConfigParser
object. To save theConfigParser
object to the file, we will invoke thewrite()
method on theConfigParser
object and pass the file pointer as the input argument. - Finally, we will close the file using the
close()
method.
After executing the above steps, we can easily convert a python dictionary to an INI file. You can observe this in the following example.
import configparser
file =open("employee1.ini","w")
config_object = configparser.ConfigParser()
myDict={'employee': {'name': 'John Doe', 'age': '35'},
'job': {'title': 'Software Engineer', 'department': 'IT', 'years_of_experience': '10'},
'address': {'street': '123 Main St.', 'city': 'San Francisco', 'state': 'CA', 'zip': '94102'}}
sections=myDict.keys()
for section in sections:
config_object.add_section(section)
for section in sections:
inner_dict=myDict[section]
fields=inner_dict.keys()
for field in fields:
value=inner_dict[field]
config_object.set(section, field, str(value))
config_object.write(file)
file.close()
The output INI file looks as follows.
The python code used in the above example is somewhat inefficient. We can implement the above logic in a more efficient way as shown below.
import configparser
file =open("employee1.ini","w")
config_object = configparser.ConfigParser()
myDict={'employee': {'name': 'John Doe', 'age': '35'},
'job': {'title': 'Software Engineer', 'department': 'IT', 'years_of_experience': '10'},
'address': {'street': '123 Main St.', 'city': 'San Francisco', 'state': 'CA', 'zip': '94102'}}
for section, options in myDict.items():
config_object.add_section(section)
for key, value in options.items():
config_object.set(section, key, str(value))
config_object.write(file)
file.close()
The output for this code will be the same as the previous code.
Conclusion
In this article, we have discussed how to convert a dictionary to an INI file in Python. To learn more about programming, you can read this article on how to append row to a dataframe in Python. You might also like this article on how to convert yaml to XML in python.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.