dktom94
dktom94

Reputation: 21

Python adding entries to a dictionary from csv file using iteration

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

Answers (1)

inspectorG4dget
inspectorG4dget

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

Related Questions