通过.tsv文件创建字典并删除值低于某个数字的键
我有一个叫做“population.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
你的程序有两个问题
- 它返回了一个空字典
{}
,而不是你创建的那个字典 - 你还没有使用过滤函数
我需要排除人口少于10,000的城市。
- 不要把变量命名成内置函数的名字
修正后的代码
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
这个内置函数(如果使用的是 Python 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)