What you're doing is iterating through the entire dict for every cell, which is kind of weird and probably not what you want to do. What you really want to do is just look in the dict and increment the key in question. So:
# first part stays mostly the same
rows = csv.reader(open("...csv") )
allCounts = {}
for row in rows:
for field in row:
allCounts[field] = allCounts.get(field, 0) + 1
That last line uses a nice little feature of dict
, which returns a default value if the key isn't found.
In your own code, there are some noteworth defects. The most significant one is the fourth and fifth lines. you extract the first field from the selected row and assign it to intVal
but then you completely mask intVal
by using it as the key when iterating over your dict. what that means is that assignment did no work at all.
The if
clause is doomed. You are checking to see if a key is in a dict, but you came up with that key by iterating over the keys from the same dict. Of course that key is in the dict.
The next issue is that your else
clause is modifying a collection over which you are iterating. Python makes no guarantees about how this will work for dicts, so don't do it
For that matter, there's no reason at all to be iterating over the dict. You can just grab whichever key-value pair you are interested in directly. What you should be iterating over is the list of integers from the file.
A CSV file is always structured as a list of values (normally separated by commas) that form rows, and the rows are separated by newlines. the CSV module preserves this view, by returning a list of lists. To drill down to the actual values, you need to iterate over each row, and then each field in that row. Your code iterates over each row, and then each key in the dict for each row, ignoring the fields.