Python使用迭代从csv文件向字典添加条目

时间:2012-11-07 01:28:28

标签: python csv iteration dictionary

我需要一个字典来迭代一个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

我可以更改哪些内容以允许将文件中的所有行添加到空字典中?

1 个答案:

答案 0 :(得分:1)

将for语句从for循环中取出:

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