Iterating through DictReader
Solution 1
DictReader()
produces a sequence of dictionaries, not just one dictionary.
for row in d:
for k, v in row.items():
Solution 2
You have to first iterate over the dict getting each row, and then iterate over the items in each row:
for row in d:
for k, v in row.items():
# Do stuff
Glitchezz
Software Engineer undergraduate. Just trying to make my way into the World of coding!
Updated on June 13, 2022Comments
-
Glitchezz almost 2 years
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!