• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Convert Dictionary to INI File in Python

Convert Dictionary to INI File in Python

Author: Aditya Raj
Last Updated: March 26, 2023

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.

Table of Contents
  1. What is the INI File Format?
  2. Convert Python Dictionary to INI File
  3. Conclusion

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 the ConfigParser() function defined in the configparser module. 
  • We will also open an INI file in write mode using the open() function. The open() 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 the add_section() method. The add_section() method takes the section name as the input argument and adds it to the ConfigParser object. 
  • To add the sections, we will first get the outer keys of the dictionary using the keys() method. The keys() 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 the ConfigParser object. 
  • After adding sections, we need to add fields for each section. For this, we will use the set() method. The set() method, when invoked on a ConfigParser 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 the ConfigParser 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 the ConfigParser object using the set() method.
  • By now, we have added all the data from the dictionary to the ConfigParser object. To save the ConfigParser object to the file, we will invoke the write() method on the ConfigParser 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.

Output INI File From Dictionary
Output INI File From Dictionary

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!

Related

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.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us