Reputation: 29
import csv
with open("DADSA RESIT CWK JULY 2018.csv", newline='') as f:
r = csv.reader(f)
database = list(r)
del database[0]
names = []
names.append([])
def fillnames(d, n):
for j in n:
for i in d:
if d[i][0] == n[j][0] and d[i][1] == n[j][1]:
n[i][2] = n[i][2]+1
else:
names.append([d[i][0], d[i][1], 0])
fillnames(database, names)
for i in names:
print(i)
The code I have here is me scanning in a csv file into a list. I then want to count how many entries share the same name, by scanning each new name into a separate list, then incrementing the number found every time I find a new one. Every time I run this code it returns "TypeError: list indices must be integers or slices, not list."
Upvotes: 0
Views: 43
Reputation: 45542
If you don't need database
:
import csv
from collections import Counter
with open("DADSA RESIT CWK JULY 2018.csv", newline='') as f:
reader = csv.reader(f)
next(reader) # discard headers
name_counts = Counter((row[0], row[1]) for row in reader)
If you do need database
:
import csv
from collections import Counter
with open("DADSA RESIT CWK JULY 2018.csv", newline='') as f:
reader = csv.reader(f)
next(reader) # discard headers
database = list(reader)
name_counts = Counter((row[0], row[1]) for row in database)
The root error in your original code is this:
for i in d:
if d[i] ...
When you do for item in somelist
in Python item
is not an index, it's the actual item. In the case of for i in d
, d
is a list of lists--so i
is one of the sublists (one of the rows). You should now see why Python would be confused by d[i]
and give "TypeError: list indices must be integers or slices, not list."
Upvotes: 2