Reputation: 21
I need a dictionary to iterate a through a csv file, make some minor changes and add entries to the dictionary from a csv file.
I have this so far, but the dictionary will only work for the very last line the file.
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
What can I change to allow all of the lines from the file to be added to the empty dictionary?
Upvotes: 2
Views: 626
Reputation: 113925
Take the return statement out of the 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
Upvotes: 1