How To Convert A CSV file into A Dictionary in Python – Definitive Guide

CSV files stores data in a comma-separated format.

You can convert a CSV file into a dictionary using the csv.dictReader(fileobj) method in Python.

Basic Example

  • The dictreader converts the CSV file into a list of dictionaries
  • Each dictionary will contain column names as keys and each row value as a value for the key.
import csv

file = 'sample.csv'

with open(file) as f:
    reader = csv.DictReader(f)

    for row in reader:
        print(row)

Output

    {'Name': 'Felix', 'Job': 'Programmer', 'Salary': '11000'}
    {'Name': 'Ram', 'Job': 'Expert', 'Salary': '90000'}
    {'Name': 'Michael', 'Job': 'Coordinator', 'Salary': '25000'}

Different methods are available to convert a CSV into a dictionary in Python. There are also things like headers that need to be handled while creating a dictionary from the CSV file.

Using DictReader

The CSV library provides the DictReader class to read the CSV file as a dictionary.

  • Open the file in the read mode
  • Pass the file object to the DictReader. Then you’ll have the reader object that contains each CSV file row as a dictionary object.

It is assumed that the CSV file uses the default separator ,. If there is any other separator, you’ll not get the proper output.

Code

The sample.csv file is read, and each line in the CSV file is created as a dictionary.

import csv

file = 'sample.csv'

with open(file) as f:
    reader = csv.DictReader(f)

    for row in reader:
        print(row)

Output

    {'Name': 'Felix', 'Job': 'Programmer', 'Salary': '11000'}

    {'Name': 'Ram', 'Job': 'Expert', 'Salary': '90000'}

    {'Name': 'Michael', 'Job': 'Coordinator', 'Salary': '25000'}

Using Dict Reader With Different Separator

To create a dictionary from a CSV file that has a different separator other than the default one ,, pass the separator using the delimiter parameter.

Code

The following code demonstrates how to read a CSV file with the ; separator.

import csv

file = 'sample_diff_separator.csv'

with open(file) as f:
    reader = csv.DictReader(f, delimiter=';')

    for row in reader:
        print(row)

Output

    {'Name': 'Felix', 'Job': 'Programmer', 'Salary': '11000'}

    {'Name': 'Ram', 'Job': 'Expert', 'Salary': '90000'}

    {'Name': 'Michael', 'Job': 'Coordinator', 'Salary': '25000'}

Create Dictionary from CSV With Header

This section teaches you how to handle the header while using the DictReader().

  • If the header is already available in the CSV file, then it’ll be read and stored in the reader.fieldnames attribute.
  • To use a custom header other than the existing one, you can assign the headers using the reader.fieldnames.

Code

The following code demonstrates how to use the custom headers while creating a dictionary from CSV with Header.

import csv

file = 'sample_Without_header.csv'

with open(file) as f:
    reader = csv.DictReader(f)

    # Assign Different Header If you would like to 
    reader.fieldnames = 'Full Name', 'Designation', 'Salary'

    for row in reader:
        print(row)

Output

    {'Full Name': 'Name', 'Designation': 'Job', 'Salary': 'Salary'}

    {'Full Name': 'Felix', 'Designation': 'Programmer', 'Salary': '11000'}

    {'Full Name': 'Ram', 'Designation': 'Expert', 'Salary': '90000'}

    {'Full Name': 'Michael', 'Designation': 'Coordinator', 'Salary': '25000'}

Create Dictionary from CSV Without Header

This section demonstrates how to create a dictionary from CSV without a header.

When the CSV file doesn’t have a header, you can use the fieldnames attribute to assign the headers while reading the CSV file.

When using this method, the dictionary keys will be as per the newly assigned headers.

Code

The following code demonstrates how to assign the fieldnames that need to be used as headers while reading the CSV file.

import csv

file = 'sample_without_header.csv'

with open(file) as f:
    reader = csv.DictReader(f, fieldnames = ('Full Name', 'Designation', 'Salary'))
    for row in reader:
        print(row)

Output

    {'Full Name': 'Felix', 'Designation': 'Programmer', 'Salary': '11000'}

    {'Full Name': 'Ram', 'Designation': 'Expert', 'Salary': '90000'}

    {'Full Name': 'Michael', 'Designation': 'Coordinator', 'Salary': '25000'}

Using Pandas to_dict() And List Orientation

In this section, you’ll learn how to use the to_dict() method available in the pandas dataframe to create a dictionary from the CSV file and use the list orientation while converting it to a dictionary.

  • Read the CSV file using the read_csv() method. You’ll get the pandas dataframe out of it
  • Use the to_dict(orient = 'list') method on the dataframe to convert the dataframe into a dictionary.
  • The orient=‘list’ parameter creates a list of values for each header.

Use this method when you want to create a single dictionary for each field available in the CSV file instead of creating a dictionary for each row available in the dictionary.

Code

The following code demonstrates how to use the to_dict() method with the list orientation to create a dictionary from the CSV file.

import pandas as pd

df = pd.read_csv('sample.csv')

your_dict = df.to_dict(orient = 'list')

your_dict

Output

    {'Name': ['Felix', 'Ram', 'Michael'],

     'Job': ['Programmer', 'Expert', 'Coordinator'],

     'Salary': [11000, 90000, 25000]}

Using Pandas to_dict() And Split Orientation

In this section, you’ll learn how to use the to_dict() method available in the pandas dataframe to create a dictionary from the CSV file and use the split orientation while converting it to a dictionary.

  • Read the CSV file using the read_csv() method. You’ll get the pandas dataframe out of it
  • Use the to_dict(orient = ‘split’) method on the dataframe to convert the dataframe into a dictionary.
  • The orient=‘split’ parameter creates keys columns for headers and the key data containing each row as a list of values.

Use this method when you want to create a dictionary for field names and another dictionary with a key as data that contains each row as a list of values.

Code

The following code demonstrates how to use the to_dict() method with the split orientation to create a dictionary from the CSV file.

import pandas as pd

df = pd.read_csv('sample.csv')

your_dict = df.to_dict(orient = 'split')

your_dict

Output

    {'index': [0, 1, 2],

     'columns': ['Name', 'Job', 'Salary'],

     'data': [['Felix', 'Programmer', 11000],
      ['Ram', 'Expert', 90000],
      ['Michael', 'Coordinator', 25000]]}

Additional Resources

Leave a Comment