Reputation: 47
I am new to Python, I have a CSV file that looks something like this:
Date, Profit
02/2019 , 100
03/2019 , 410
03/2019 , 300
04/2019 , 200
I need to write a code in Python that print how many unique dates is in the file
Here is what I have so far, but It only print # 1
import os
import csv
with open('budget_data.csv') as file:
reader = csv.reader(file,delimiter=',')
t_dates = [1]
for row in reader:
if row[0] not in row:
t_dates.append(row[0])
print(len(t_dates))
Upvotes: 1
Views: 659
Reputation: 11992
you can use DictReader
that will map the csv headers to the items as a key. You can then use set comprehension to get a list of unique dates and count the length of them.
import csv
with open('test.dat') as file:
reader = csv.DictReader(file, delimiter=',')
print(len({row['Date'] for row in reader}))
Upvotes: 2