Python – Convert CSV to List of Dictionaries

5/5 - (6 votes)

Convert a CSV file to a list of Python dictionaries in three steps:

  • Create a CSV file object f using open("my_file.csv") and pass it in the csv.DictReader(f) method.
  • The return value is an iterable of dictionaries, one per row in the CSV file. Each dictionary maps the column header from the first row to the specific row value.
  • As the last step, convert the iterable of dictionaries to a list using the Python built-in list() function.

Let’s have a look at a simple example to demonstrate this solution next!

Basic Solution: CSV to List of Dicts – Example

Here’s the content of an example CSV file "my_file.csv" used in our code snippet below:

Name,Job,Age,Income
Alice,Programmer,23,110000
Bob,Executive,34,90000
Carl,Sales,45,50000

If you visualize this CSV in table form, it looks like this:

NameJobAgeIncome
AliceProgrammer23110000
BobExecutive3490000
CarlSales4550000

Here’s the code to convert that CSV file to a list of dictionaries, one dictionary per row by using the csv.DictReader(file) function:

import csv


csv_filename = 'my_file.csv'

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

lst = list(*reader)

A dictionary is a data structure that maps keys to values.

The result of the previous code snippet is a list of dictionaries. The first row of the CSV is used as a header to determine the keys of the dictionary that are mapped to the values defined in the individual rows of the CSV file:

[{'Name': 'Alice', 'Job': 'Programmer', 'Age': '23', 'Income': '110000'}
{'Name': 'Bob', 'Job': 'Executive', 'Age': '34', 'Income': '90000'}
{'Name': 'Carl', 'Job': 'Sales', 'Age': '45', 'Income': '50000'}]

The csv.DictReader(f) method takes a file object f as an input argument. So, you first need to open the file using the built-in Python open() function.

🪲 Note: A common error is to pass the filename as a string—but this doesn’t work! The csv.DictReader(f) method expects a file object as a required argument.

One-Liner Solution: CSV to List of Dicts

I love Python one-liners. That’s why I have written a book on those after all. 🙂

So, can we convert a CSV to a list of dictionaries in a single line of Python?

Of course, we can!

Here’s the one-liner that accomplishes the same as the code discussed before:

import csv; lst = list(*csv.DictReader(open('my_file.csv')))

💡 Explanation: We import the csv module, use the semicolon ; to package two statements in one line, unpack * all rows from the csv.DictReader() output as arguments into the list() built-in function.

The result is stored in the variable lst that now holds the same list as before:

[{'Name': 'Alice', 'Job': 'Programmer', 'Age': '23', 'Income': '110000'}
{'Name': 'Bob', 'Job': 'Executive', 'Age': '34', 'Income': '90000'}
{'Name': 'Carl', 'Job': 'Sales', 'Age': '45', 'Income': '50000'}]

Here’s an alternative that is similar but also prints the list in a single line—now the unpacking happens into the bracket notation []:

import csv; lst=[*csv.DictReader(open('my_file.csv'))]; print(lst)

The output is a list of dictionaries, one per (non-header) row of the original CSV:

[{'Name': 'Alice', 'Job': 'Programmer', 'Age': '23', 'Income': '110000'}, 
 {'Name': 'Bob', 'Job': 'Executive', 'Age': '34', 'Income': '90000'}, 
 {'Name': 'Carl', 'Job': 'Sales', 'Age': '45', 'Income': '50000'}]

If you’re interested in learning one-liners as well, feel free to check out my book:

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!