python - 通过.tsv文件创建字典并消除值低于特定数字的键

标签 python csv

我收到了一个名为“population.tsv”的 .tsv 文件,其中包含许多城市的人口信息。我必须创建一本字典,其中城市是关键,人口是其值。创建字典后,我必须消除人口少于 10,000 的城市。怎么了?

def Dictionary():
    d={}
    with open("population.tsv") as f:
        for line in f:
            (key, value)=line.split()
            d[int(key)]=val
    return {}
list=Dictionary()
print(list)

最佳答案

您的程序有两个问题

  1. 它返回一个空字典{},而不是您创建的字典
  2. 你还没加入过滤功能我得把人口少于10000的城市剔除。
  3. 不应将变量命名为内置变量

固定代码

def Dictionary():
    d={}
    with open("population.tsv") as f:
        for line in f:
            (key, value)=line.split()
            key = int(val)
            #I have to eliminate the cities which have less than 10,000 people
            if key < 10000: 
                d[int(key)]=val
    #return {}
    #You want to return the created dictionary
    return d
#list=Dictionary()
# You do not wan't to name a variable to a built-in
lst = Dictionary()

print(lst)

请注意,您还可以通过传递生成器表达式或直接的字典理解来使用内置的 dict (如果使用 Py 2.7)

def Dictionary():
    with open("population.tsv") as f:
        {k: v for k,v in (map(int, line.split()) for line in f) if k < 10000}
        #If using Py < Py 2.7
        #dict((k, v) for k,v in (map(int, line.split()) for line in f) if k < 10000)

关于python - 通过.tsv文件创建字典并消除值低于特定数字的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15080143/

相关文章:

python - 如何在 Eclipse 中使用 python 静态检查器?

python - 私有(private)和公共(public)包模块?

python - Pyautogui 截图 - NameError : name 'Image' is not defined

python - 设置 py2app 以运行 selenium

java - OpenCSV - 将多个 CSV 列映射到单个 bean 属性

mysql - 如何上传文件(csv 或文本)并在 Zope 框架中读取内容

csv - 尝试写入 CSV 记录时出现错误 "the trait ` std::convert::AsRef<[u8] >` is not implemented for ` u 8`"

python - Pandas 数据框 CSV 减少磁盘大小

python - 将文件读取到字符串(python)

c++ - 从 CSV 中读取并存储在 Vector 中