• 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 INI File to Dictionary in Python

Convert INI File to Dictionary in Python

Author: Aditya Raj
Last Updated: March 27, 2023

INI files are one of the simplest configuration files that we use in software systems. In this article, we will discuss how to convert an INI file to a python dictionary.

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

What is the INI File Format?

INI (short for “initialization”) file format is a plain text file format that is commonly used to store configuration settings for computer programs. INI files have a .ini file extension.

Each INI file consists of different sections containing data in the form of key-value pairs. The sections are defined using square brackets ([]) and the key-value pairs are separated by an equal sign (=) or a colon (:). 

For instance, consider the following example.

[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 INI file represents configuration data for an employee. It consists of several sections, each containing key-value pairs.

  • The [employee] section contains the employee’s name and age.
  • [job] section contains information about the employee’s job, including the job title, department, and years of experience.
  • The [address] section contains the employee’s address information, including the street address, city, state, and ZIP code.

Each key-value pair within a section represents a single configuration setting. Here, the key represents the name of the setting and the value represents the value of the setting. For example, the "name=John Doe" key-value pair in the [employee] section indicates that the employee’s name is "John Doe". Similarly, the "title=Software Engineer" key-value pair in the [job] section indicates that the employee’s job title is "Software Engineer".

The above ini file can be stored in a file as shown below.

INI Configuration File
INI Configuration File

INI files are easy to read and edit with any text editor. They are widely used on Windows and other operating systems for storing configuration data for various applications. However, in recent years, INI files have been largely replaced by more sophisticated configuration file formats, such as XML, JSON, and YAML.

Convert INI File to Python dictionary

To convert an INI file to a python dictionary, we will use the configparser module. We will use the following steps to convert an INI file to a python dictionary.

  • First, we will open the ini configuration file in read mode using the open() function. The open() function takes the file name as its first input argument and the python literal “r” as its second argument. After execution, it returns a file pointer.
  • Next, we will create an empty ConfigParser object using the ConfigParser() function defined in the configparser module. We will also create an empty dictionary to store the output dictionary.
  • After creating the ConfigParser object, we will read the file into the ConfigParser object. For this, we will use the read_file() method. The read_file() method, when invoked on an empty ConfigParser object, takes the file pointer as its input argument and loads the file contents into the ConfigParser object. 
  • The ConfigParser object stores data in different sections as shown in the example in the previous section. We will get the name of all the sections in the ConfigParser object using the sections() method. The sections() method, when invoked on a ConfigParser object, returns a list of section names in the configuration file.
  • In each section of the configuration file, there are different key-value pairs to store the data. We can get the key-value pairs in a section using the items() method. The items() method, when invoked on a ConfigParser object, takes the section name as its input argument and returns a list of tuples containing the key-value pairs in the given section.
  • Once we get the list of key-value pairs in a given section, we will convert the list of tuples into a dictionary using the dict() function. The dict() function takes the list of tuples as its input arguments and returns a python dictionary. 
  • After creating dictionaries for key-value pairs in each section, we will assign the section name as the key and the corresponding dictionary as the value to the output dictionary.

After executing the above steps, we will get the python dictionary containing data from the INI file. You can observe this in the following example.

import configparser
config_object = configparser.ConfigParser()
file =open("employee.ini","r")
config_object.read_file(file)
output_dict=dict()
sections=config_object.sections()
for section in sections:
    items=config_object.items(section)
    output_dict[section]=dict(items)
print("The output dictionary is:")
print(output_dict)

Output:

The output dictionary is:
{'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'}}

Instead of using a for loop, you can also use dictionary comprehension to convert an INI file to a python dictionary as shown below.

import configparser
config_object = configparser.ConfigParser()
file =open("employee.ini","r")
config_object.read_file(file)
output_dict={s:dict(config_object.items(s)) for s in config_object.sections()}
print("The output dictionary is:")
print(output_dict)

Output:

The output dictionary is:
{'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'}}

You can observe that the above code works in a similar manner to the previous code using for loops.

Conclusion

In this article, we discussed two ways to convert an INI configuration file to a python dictionary. To learn more about file conversions, you can read this article on how to convert a python dictionary to INI file. You might also like this article on how to convert a XML file to YAML.

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