Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through DictReader

I have read a csv file using,

with open('test.csv', newline='') as csv_file:
        #restval = blank columns = - /// restkey = extra columns +
        d = csv.DictReader(csv_file, fieldnames=None, restkey='+', restval='-', delimiter=',', quotechar='"')

I would like to iterate through the created dictionary to find blank values within the csv. I have tried:

for k, v in d.items()
#Do stuff

However I get the error: AttributeError: 'DictReader' object has no attribute 'items'

Is it right in saying that the values stored in d is a dictionary of dictionaries?

Coming from C# I would have stored the csv in a multidimensional array with a nested for loop to iterate through the values. Unfortunately I'm still new to Python - any help + explanations will be appreciated!

like image 944
Glitchezz Avatar asked Feb 05 '14 00:02

Glitchezz


People also ask

What is the use of DictReader ()?

DictReader() . csv. Reader() allows you to access CSV data using indexes and is ideal for simple CSV files.

How does DictReader work in Python?

DictReader class operates like a regular reader but maps the information read into a dictionary. The keys for the dictionary can be passed in with the fieldnames parameter or inferred from the first row of the CSV file.


1 Answers

DictReader() produces a sequence of dictionaries, not just one dictionary.

for row in d:
    for k, v in row.items():
like image 186
Martijn Pieters Avatar answered Oct 06 '22 20:10

Martijn Pieters