Joe
Joe

Reputation: 512

invalid python syntax in my 'for' loop

def citypop():
  import csv                                  
  F = open("Top5000Population.txt")           
  csvF = csv.reader(F)
  D = {}
  with csvF for row in csvF:
      city,state,population = row[0],row[1],row[2] 
      population = population.replace(',','') 
      population = int(population)
      city = city.upper()[:12]
      D[(city, state)] = population
  return D

The function citypop() returns a dict with (city,state) as the key and the population of that city (in that state) as the value.

I keep getting a syntax error .. am I not understanding the csv module correctly?

EDIT: thanks for the help guys....this should work but now all of the sudden I am getting the error

 for city, state, population in reader(F):       File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/encodings/ascii.py", line 26, in decode         return codecs.ascii_decode(input, self.errors[0]) UnicodeDecodeError: 'ascii' codec can't decode byte 0xa4 in position 7062: ordinal not in range(128)  

When I run the test cases .... any suggestions?

Upvotes: 2

Views: 789

Answers (2)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

Think you mean this when tried to use with statement - in such a case file will be closed right after leaving code under it:

from csv import reader

def citypop():
  D = {}
  with open("Top5000Population.txt") as F:
    for city, state, population in reader(F):
      city = city.upper()[:12]
      D[(city, state)] = int(population.replace(',',''))
  return D

OR:

def citypop():
  with open("Top5000Population.txt") as F:
    return dict(((x.upper()[:12], y), int(z.replace(',', '')) for x, y, z in reader(F))

Upvotes: 3

kevintodisco
kevintodisco

Reputation: 5181

I think you are misunderstanding Python's with statement. Making line 6:

for row in csvF:

should fix the problem.

For reference, the with statement is essentially the same as the using statement in C#; it declares the scope of a resource that you will need to unload or release when you are done with it.

Upvotes: 1

Related Questions