You can do this very simply using pandas.

import pandas as pd

# get only the columns you want from the csv file
df = pd.read_csv(target_path + target_file, usecols=['Column Name1', 'Column Name2'])
result = df.to_dict(orient='records')

Sources:

  • pandas.read_csv
  • pandas.DataFrame.to_dict
Answer from Onel Harrison on Stack Overflow
🌐
University of Washington
courses.cs.washington.edu › courses › cse140 › 13wi › csv-parsing.html
How to parse csv formatted files using csv.DictReader?
This guide uses the following example file, people.csv. id,name,age,height,weight 1,Alice,20,62,120.6 2,Freddie,21,74,190.6 3,Bob,17,68,120.0 · Your Python code must import the csv library. ... Open the file by calling open and then csv.DictReader.
Discussions

python csv to dictionary using csv or pandas module - Stack Overflow
I am using Python's csv.DictReader to read in values from a CSV file to create a dictionary where keys are first row or headers in the CSV and other rows are values. It works perfectly as expected ... More on stackoverflow.com
🌐 stackoverflow.com
python - csv.DictReader / csv.DictWriter vs Panda library data Frame - - Stack Overflow
I am trying to write a program in Python which would: Reads data from a CSV file, with data ordered by date select some keys and values, by finding the last 365 days (past 365 days from the last d... More on stackoverflow.com
🌐 stackoverflow.com
python - Load csv file as a dataframe - Stack Overflow
This is a noob question, but without using Pandas (pd.read) how can I import a CSV file and load it to a DataFrame object so I can call it (e.g. print (loaded_file) ) and print the contents of the ... More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
When using reader or DictReader from the csv module, why do you need to access the return value while the file is still open?
because leaving the with-block calls the object's __exit__() function https://peps.python.org/pep-0343/ which for a filehandle is equivalent to a close() https://docs.python.org/3/reference/datamodel.html#object.__exit__ so after you jump out of the with-block's indent, the file handle's close function has been called and it's no longer readable More on reddit.com
🌐 r/learnpython
11
3
August 7, 2023
🌐
Medium
medium.com › @3valuedlogic › using-python-csv-3-dictreader-e4814ce2e44
Using Python CSV #3 — DictReader. Python’s csv module allows you to work… | by David W. Agler | Medium
December 22, 2022 - If we have 50 columns of data, ... newline='') as infile: reader = csv.DictReader(infile) for row in reader: print(row['age']) # 'age' fieldname!...
🌐
Wordpress
statcompute.wordpress.com › 2018 › 10 › 21 › import-csv-as-dictionary-list
Import CSV as Dictionary List – Yet Another Blog in Statistical Computing
October 22, 2018 - from csv import DictReader from pprint import pprint ### EXAMINE 3 ROWS OF DATA with open("Downloads/nycflights.csv") as f: d = DictReader(f) l = [next(d) for i in xrange(3)] pprint(l[0]) #{'air_time': '227', # 'arr_delay': '11', # 'arr_time': '830', # 'carrier': 'UA', # 'day': '1', # 'dep_delay': '2', # 'dep_time': '517', # 'dest': 'IAH', # 'distance': '1400', # 'flight': '1545', # 'hour': '5', # 'minute': '17', # 'month': '1', # 'origin': 'EWR', # 'tailnum': 'N14228', # 'year': '2013'} A solution to address the aforementioned issue is first to import the csv file into a Pandas DataFrame and then to convert the DataFrame to the list of dictionaries, as shown in the code snippet below.
Find elsewhere
🌐
Delft Stack
delftstack.com › home › howto › python › python csv to dictionary
How to Convert CSV Into Dictionary in Python | Delft Stack
March 13, 2025 - We then read the CSV file using pd.read_csv, which loads the data into a DataFrame. The to_dict method is called with the orient='records' argument, which converts the DataFrame into a list of dictionaries, where each dictionary corresponds to a row in the DataFrame.
🌐
Python
docs.python.org › 3 › library › csv.html
csv — CSV File Reading and Writing
Return the next row of the reader’s iterable object as a list (if the object was returned from reader()) or a dict (if it is a DictReader instance), parsed according to the current Dialect. Usually you should call this as next(reader). Reader objects have the following public attributes: ... A read-only description of the dialect in use by the parser. ... The number of lines read from the source iterator. This is not the same as the number of records returned, as records can span multiple lines. DictReader objects have the following public attribute:
🌐
Sling Academy
slingacademy.com › article › python-how-to-read-a-csv-file-and-convert-it-to-a-dictionary
Python: How to read a CSV file and convert it to a dictionary - Sling Academy
import csv filename = 'example.csv' # Open the CSV file with open(filename, mode='r') as csvfile: # create a csv reader object from the file object csvreader = csv.DictReader(csvfile) # Convert to a list of dictionaries data = [row for row in csvreader] print(data) The code snippet above will read a csv file named ‘example.csv’ and print a list of dictionaries, where each dictionary represents a row in the CSV file, with the heading being the key.
🌐
Linux Hint
linuxhint.com › use-python-csv-dictreader
Linux Hint – Linux Hint
December 2, 2021 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
Reddit
reddit.com › r/learnpython › when using reader or dictreader from the csv module, why do you need to access the return value while the file is still open?
r/learnpython on Reddit: When using reader or DictReader from the csv module, why do you need to access the return value while the file is still open?
August 7, 2023 -

Ok, this will make more sense. Why does this work:

import csv

with open('test.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        print(row)

But this gives an error that the file is closed:

import csv

with open('test.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file)

for row in csv_reader:
    print(row)

Traceback (most recent call last):
File "c:\Users\John\Documents\Python\test_project\test2.py", line 5, in <module> for row in csv_reader: File "C:\Users\John\AppData\Local\Programs\Python\Python311\Lib\csv.py", line 110, in next self.fieldnames File "C:\Users\John\AppData\Local\Programs\Python\Python311\Lib\csv.py", line 97, in fieldnames self._fieldnames = next(self.reader) ^ 
ValueError: I/O operation on closed file.

Does DictReader (and also reader) not just run once and return a value? Why is csv_file being accessed after the line it's used in?

Thanks!

🌐
Brodan
brodan.biz › blog › parsing-csv-files-with-python
Parsing CSV Files with Python's DictReader - Brodan.biz
August 24, 2018 - A brief over of Python's DictReader class and how to use it to treat CSV files like dictionaries.
Top answer
1 of 2
2

csv.reader

Given your desired output, you do not need to use dict or, consequently, csv.DictReader. Instead, just use csv.reader, which returns an iterator. Then use next and list to extract headers and data respectively:

from io import StringIO
import csv

x = StringIO("""play,weather,temperature
yes,sunny,77
no,rainy,60
yes,windy,70""")

# replace x with open('file.csv', 'r')
with x as fin:
    reader = csv.reader(fin)
    headers = next(reader)  # get headers from first row
    data = list(reader)     # exhaust iterator from second row onwards

The result is a list of headers, and a list of lists for data:

print(headers)

['play', 'weather', 'temperature']

print(data)

[['yes', 'sunny', '77'],
 ['no', 'rainy', '60'],
 ['yes', 'windy', '70']]

pandas

If you are willing to use a 3rd party library, Pandas may be a better option as it handles type conversion and indexing more conveniently:

import pandas as pd

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

The result is a pd.DataFrame object:

print(df)

  play weather  temperature
0  yes   sunny           77
1   no   rainy           60
2  yes   windy           70

print(type(df))

<class 'pandas.core.frame.DataFrame'>
2 of 2
1

DictReader returns a file-like object. It still reads the data from the csv file in one row at a time, but the returned rows are ordered dictionaries instead of lists.

If your files is:

play,weather,temperature
yes,sunny,77
no,rainny,60
yes,windy,70

Then you can use DictReader in the following way:

with open('path/to/file.csv') as fp:
    header = fp.readline().strip().split(',')
    dreader = DictReader(fp, header)
    data = list(dreader)

In this case, data will be a list of OrderedDict objects with the mapping from the headers to each item in the row.

data
#returns:
[OrderedDict([('play', 'yes'), ('weather', 'sunny'), ('temperature', '77')]),
 OrderedDict([('play', 'no'), ('weather', 'rainny'), ('temperature', '60')]),
 OrderedDict([('play', 'yes'), ('weather', 'windy'), ('temperature', '70')])]
🌐
Stack Overflow
stackoverflow.com › questions › 41155239 › how-to-use-csv-dictreader › 41155479
python - How to use csv.DictReader - Stack Overflow
import csv def read_file(filename, col_list): with open(filename, 'r') as f: reader = csv.DictReader(f) final_dict = {} x = 0 while x < len(col_list): print 'X IS ' + str(x) this_list = [] print 'list before adding stuff: ' #test print this_list ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › working-csv-files-python
Working with csv files in Python - GeeksforGeeks
We can use Pandas to write CSV files. It can done by using pd.DataFrame() function. In this example, the Pandas library is used to convert a list of dictionaries (mydict) into a DataFrame, representing tabular data.
Published   August 5, 2025
🌐
Runebook.dev
runebook.dev › en › docs › python › library › csv › csv.DictReader
Beyond DictReader: A Friendly Guide to CSV Processing in Python
When you do this, DictReader treats the first line of the file as data, not headers. ... import csv import io data_no_header = """ Alice,30,NY Bob,25,LA """ csvfile = io.StringIO(data_no_header) # Specify the desired column names FIELD_NAMES = ['Person', 'Years', 'Location'] # Pass the list to fieldnames.
🌐
ZetCode
zetcode.com › python › csv
Python CSV - read, write CSV in Python
January 29, 2024 - Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes. ... To use Python CSV module, we import csv. The csv.reader method returns a reader object which iterates over lines in the given CSV file. ... The numbers.csv file contains numbers. ... #!/usr/bin/python import csv with open('numbers.csv', 'r') as f: reader = csv.reader(f) for row in reader: for e in row: print(e) In the code example, we open the numbers.csv for reading and read its contents.
🌐
Real Python
realpython.com › videos › reading-csvs-pythons-csv-module
Reading CSVs With Python's "csv" Module (Video) – Real Python
@Kim If you don’t explicitly provide a list of field names for your records, then DictReader will assume the first line in the CSV file is the header. It will try to get those field names from there, always skipping the first line during iteration: name,department,birthday month Joe Doe,IT,1999-01-01 Anna Smith,HR,2001-12-31 Bob Brown,Sales,2002-15-31 · >>> import csv >>> with open(r"example.csv") as csv_file: ...
Published   March 1, 2019
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.read_csv.html
pandas.read_csv — pandas 3.0.4 documentation - PyData |
Read a comma-separated values (csv) file into DataFrame. Also supports optionally iterating or breaking of the file into chunks. Additional help can be found in the online docs for IO Tools.