The csv.DictReader function expects a file object as its first argument, not a string. So, it always is used with normal file io.

for example,

with open('input.csv', 'r') as f:
    reader = csv.DictReader(f, delimiter=' ', fieldnames = ['Device', 'tps', 'kB_read/s' ,'kB_wrtn/s', 'kB_dscd/s', 'kB_read', 'kB_wrtn', 'kB_dscd'])

And, you can iterate the reader (i.e., iterable of dicts) row by row.

for row in reader:
    print(row)

The row variable contains dictionary-like object that you can easily access by key, for example, row['Device'].

Answer from JayPeerachai 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 example finds the oldest person ... == None or max_age < age: max_age = age oldest_person = row["name"] if max_age != None: print "The oldest person is %s, who is %d years old."...
Discussions

Python csv.DictReader - Stack Overflow
I was trying different codes with csv.DictReader to read csv file into a variable. More on stackoverflow.com
🌐 stackoverflow.com
What does .dictreader() do?
hi guys! I have a question. I know when we use .dictreader() we use csv module to make a dictionary out of the csv file, so it’s easier to use for programming, but I don’t get it how does this dictionary look like exactly. first, I thought it uses titles in the first line to make keys, ... More on discuss.codecademy.com
🌐 discuss.codecademy.com
0
0
September 27, 2023
Using Python's csv.dictreader to search for specific key to then print its value - Stack Overflow
My program will ask the user for the title (thus the key) they are looking for, and present the value (which is the 2nd column) to the screen using the print function. My problem is how to use the csv.dictreader to search for a specific key, and print its value. Sample Data: Below is an example of ... More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
Brodan
brodan.biz › blog › parsing-csv-files-with-python
Parsing CSV Files with Python's DictReader - Brodan.biz
August 24, 2018 - import csv with open('videos.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row['id'])
🌐
Medium
medium.com › @3valuedlogic › using-python-csv-3-dictreader-e4814ce2e44
Using Python CSV #3 — DictReader
December 22, 2022 - Our fieldnames should be the first row (the header): ‘name’, ‘age’, and ‘account’. These should map to the name, age, and account size of each person. Let’s check by printing out each dictionary. We can do this by printing each item in the DictReader object:
🌐
ProgramCreek
programcreek.com › python › example › 1483 › csv.DictReader
Python Examples of csv.DictReader
def import_business_data_relations(self, data_source): """ Imports business data relations """ if isinstance(data_source, str): data_source = [data_source] for path in data_source: if os.path.isabs(path): if os.path.isfile(os.path.join(path)): relations = csv.DictReader(open(path, "r")) RelationImporter().import_relations(relations) else: utils.print_message("No file found at indicated location: {0}".format(path)) sys.exit() else: utils.print_message( "ERROR: The specified file path appears to be relative.
🌐
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.
🌐
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
Find elsewhere
🌐
DEV Community
dev.to › bowmanjd › flexible-csv-handling-in-python-with-dictreader-and-dictwriter-3hae
Flexible CSV Handling in Python with DictReader and DictWriter - DEV Community
February 9, 2026 - inpath = Path("sample.csv") outpath = Path("out/transformed.csv") args = {"newline": "", "encoding": "utf-8-sig"} with inpath.open("r", **args) as infile, outpath.open("w", **args) as outfile: reader = csv.DictReader(infile) writer = csv.DictWriter(outfile, ["Firstname", "Lastname", "Username"]) As you may already be aware, it is possible to pass a dictionary of keyword arguments to a Python function. Because both open() functions needed the same newline and encoding arguments, I built a dictionary with those then pass it to each open(), prefixing the necessary **. That way I don't repeat myself. The above (incomplete) example can be filled out with row handling logic so that each row can be read, transformed, then written.
🌐
Python Pool
pythonpool.com › home › blog › csv dicteader doesn’t have to be hard
CSV Dicteader Doesn't Have To Be Hard - Python Pool
December 18, 2021 - So, in the above example, what we have done is we first imported DictReader class from the CSV module. After that, we opened the file airtarvel.csv in “read” mode, which consists of the number of monthly travelers in 1958, 1959, and 1960.
🌐
Real Python
realpython.com › videos › reading-csvs-pythons-csv-module
Reading CSVs With Python's "csv" Module (Video) – Real Python
I think you should try downloading the file or using: docs.python.org/3/library/urllib.request.html#urllib.request.urlopen · Kim on Oct. 31, 2021 ... I just went through this tutorial and with DictReader, it appears to have iterated rows through all of the rows, but only printed rows 0 and 2 and bypassed 1. Here is the snippet, which I believe is identical to the script in the tutorial. with open(r'C:\Users\xxxx\xxxx\csv_example.txt') as csv_file: csv_reader = csv.DictReader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count ==0: print(f'Column names are {", ".join(row)}') line_count += 1 else: print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.') line_count += 1 print(f'Processed {line_count} lines.')
Published   March 1, 2019
🌐
Codecademy Forums
discuss.codecademy.com › data science
What does .dictreader() do? - Data Science - Codecademy Forums
September 27, 2023 - hi guys! I have a question. I know when we use .dictreader() we use csv module to make a dictionary out of the csv file, so it’s easier to use for programming, but I don’t get it how does this dictionary look like exactly. first, I thought it uses titles in the first line to make keys, and then unzip the rest into these keys based on their index. but now, I see it like this, which doesn’t make sense. import csv with open("cool_csv.csv") as cool_csv_file : cool_csv_dict = csv.DictReader(coo...
🌐
Programiz
programiz.com › python-programming › reading-csv-files
Reading CSV files in Python
The csv.DictReader() returned an OrderedDict type for each row. That's why we used dict() to convert each row to a dictionary. Notice that we have explicitly used the dict() method to create dictionaries inside the for loop. ... Note: Starting from Python 3.8, csv.DictReader() returns a dictionary for each row, and we do not need to use dict() explicitly.
Top answer
1 of 2
2

The documentation you linked to provides half the answer:

class csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)

[...] maps the information read into a dict whose keys are given by the optional fieldnames parameter. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames.

It would seem that if the fieldnames parameter is passed, the given file will not have its first record interpreted as headers (the parameter will be used instead).

# file_data is the text of the file, not the filename
reader = csv.DictReader(file_data, ("title", "value"))
for i in reader:
  list_of_stuff.append(i)

which will (apparently; I've been having trouble with it) produce the following data structure:

[{"title": "Mamer", "value": "285713:13"},
 {"title": "Champhol", "value": "461034:2"},
 {"title": "Station Palais", "value": "972811:0"}]

which may need to be further massaged into a title-to-value mapping by something like this:

data = {}
for i in list_of_stuff:
  data[i["title"]] = i["value"]

Now just use the keys and values of data to complete your task.


And here it is as a dictionary comprehension:

data = {row["title"]: row["value"] for row in csv.DictReader(file_data, ("title", "value"))}
2 of 2
2

The currently accepted answer is fine, but there's a slightly more direct way of getting at the data. The dict() constructor in Python can take any iterable.

In addition, your code might have issues on Python 3, because Python 3's csv module expects the file to be opened in text mode, not binary mode. You can make your code compatible with 2 and 3 by using io.open instead of open.

import csv
import io

with io.open('anchor_summary2.csv', 'r', newline='', encoding='utf-8') as f:
    data = dict(csv.reader(f))

print(data['Champhol'])

As a warning, if your csv file has two rows with the same value in the first column, the later value will overwrite the earlier value. (This is also true of the other posted solution.)

If your program really is only supposed to print the result, there's really no reason to build a keyed dictionary.

import csv
import io


# Python 2/3 compat
try:
    input = raw_input
except NameError:
    pass


def main():
    # Case-insensitive & leading/trailing whitespace insensitive
    user_city = input('Enter a city: ').strip().lower()

    with io.open('anchor_summary2.csv', 'r', newline='', encoding='utf-8') as f:
        for city, value in csv.reader(f):
            if user_city == city.lower():
                print(value)
                break
        else:
            print("City not found.")

if __name __ == '__main__':
    main()

The advantage of this technique is that the csv isn't loaded into memory and the data is only iterated over once. I also added a little code the calls lower on both the keys to make the match case-insensitive. Another advantage is if the city the user requests is near the top of the file, it returns almost immediately and stops looking through the file.

With all that said, if searching performance is your primary consideration, you should consider storing the data in a database.

🌐
ZetCode
zetcode.com › python › csv
Python CSV - read, write CSV in Python
January 29, 2024 - #!/usr/bin/python # read_csv3.py import csv with open('values.csv', 'r') as f: reader = csv.DictReader(f) for row in reader: print(row['min'], row['avg'], row['max']) The example reads the values from the values.csv file using the csv.DictReader. for row in reader: print(row['min'], row['avg'], ...
🌐
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!

🌐
GITNUX
blog.gitnux.com › home › programming-advice
How do I use the csv.DictReader class in Python to read a CSV file? • GITNUX
August 25, 2023 - 3. Create a `DictReader` object, passing the file object as an argument: ... Here’s a complete example that reads a CSV file named `example.csv` and prints each row as an ordered dictionary:
🌐
Python Beginners
python-adv-web-apps.readthedocs.io › en › latest › csv.html
CSV Files — Python Beginners documentation - Read the Docs
The code above will print 46 lines, ... for-loop to read from all rows in the CSV. Close the file. The csv.DictReader() method is used to convert a CSV file to a Python dictionary....