~/python/python-code-how-read-csv-with-header-array-dictionary.md

Python Code - How To Read CSV with Headers into an Array of Dictionary

1 min readOctober 05, 2021by Gorav Singal#python#csv
// TL;DR

Use Python's csv.DictReader() to read a CSV file with headers and convert each row into a dictionary with column names as keys.

Python Code - How To Read CSV with Headers into an Array of Dictionary

Introduction

Lets assume we have a csv something similar to following:

firstname,lastname,address,city,state,pin
John,Doe,120 jefferson st.,Riverside, NJ, 08075
Jack,McGinnis,220 hobo Av.,Phila, PA,09119
"John ""Da Man""",Repici,120 Jefferson St.,Riverside, NJ,08075
Stephen,Tyler,"7452 Terrace ""At the Plaza"" road",SomeTown,SD, 91234
,Blankman,,SomeTown, SD, 00298
"Joan ""the bone"", Anne",Jet,"9th, at Terrace plc",Desert City,CO,00123

Python code to read CSV into Array of Dictionary

def read(filepath):
  content = []
  with open(filepath) as csvfile:
    csv_reader = csv.reader(csvfile)
    headers = next(csv_reader)

    for row in csv_reader:
      row_data = {key: value for key, value in zip(headers, row)}
      content.append(row_data)

  return content

content = read("addresses.csv")
print(content)

The Output as Array of Dictionary

[{
  'firstname': 'John',
  'lastname': 'Doe',
  'address': '120 jefferson st.',
  'city': 'Riverside',
  'state': ' NJ',
  'pin': ' 08075'
}, {
  'firstname': 'Jack',
  'lastname': 'McGinnis',
  'address': '220 hobo Av.',
  'city': 'Phila',
  'state': ' PA',
  'pin': '09119'
}, {
  'firstname': 'John "Da Man"',
  'lastname': 'Repici',
  'address': '120 Jefferson St.',
  'city': 'Riverside',
  'state': ' NJ',
  'pin': '08075'
}, {
  'firstname': 'Stephen',
  'lastname': 'Tyler',
  'address': '7452 Terrace "At the Plaza" road',
  'city': 'SomeTown',
  'state': 'SD',
  'pin': ' 91234'
}, {
  'firstname': '',
  'lastname': 'Blankman',
  'address': '',
  'city': 'SomeTown',
  'state': ' SD',
  'pin': ' 00298'
}, {
  'firstname': 'Joan "the bone", Anne',
  'lastname': 'Jet',
  'address': '9th, at Terrace plc',
  'city': 'Desert City',
  'state': 'CO',
  'pin': '00123'
}]

Next

See how we can read CSV into an Array of arrays

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Python Code - How To Read CSV into an Array of Arrays

Python Code - How To Read CSV into an Array of Arrays

Introduction In last post, we saw How to read CSV with Headers into Dictionary…

Python SMTP Email Code - How to Send HTML Email from Python Code with Authentication at SMTP Server

Python SMTP Email Code - How to Send HTML Email from Python Code with Authentication at SMTP Server

Introduction This post has the complete code to send email through smtp server…

Python Build Quality Gates with Pylint and Unittest Coverage Thresholds

Python Build Quality Gates with Pylint and Unittest Coverage Thresholds

Introduction It is very important to introduce few process so that your code and…

Python - How to Implement Timed-Function which gets Timeout After Specified Max Timeout Value

Python - How to Implement Timed-Function which gets Timeout After Specified Max Timeout Value

Introduction We often require to execute in timed manner, i.e. to specify a max…

How to Solve Circular Import Error in Python

How to Solve Circular Import Error in Python

Introduction To give some context, I have two python files. (Both in same folder…

Python - Some useful Pytest Commands

Python - Some useful Pytest Commands

Introduction In this post, we will explore some useful command line options for…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…