2

我需要一个字典来遍历 csv 文件,进行一些小的更改并将条目从 csv 文件添加到字典中。

到目前为止我有这个,但字典只适用于文件的最后一行。

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

我可以更改什么以允许将文件中的所有行添加到空字典中?

4

1 回答 1

1

从 for 循环中取出 return 语句:

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
于 2012-11-07T01:34:07.280 回答