【问题标题】:Python adding entries to a dictionary from csv file using iterationPython使用迭代将条目从csv文件添加到字典
【发布时间】:2012-10-27 01:17:18
【问题描述】:

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

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

【问题讨论】:

  • 需要关闭F。考虑使用with open("Top5000Population.txt") as F构造

标签: python csv iteration dictionary


【解决方案1】:

将return语句从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

【讨论】:

    猜你喜欢
    • 2020-02-19
    • 2015-06-24
    • 1970-01-01
    • 2022-12-03
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多