你的程序有两个问题
- 它返回一个空字典
{}
而不是您创建的字典
- 你还没有加入过滤功能
I have to eliminate the cities which have less than 10,000 people.
- 您不应该将变量命名为内置
固定代码
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
通过传递生成器表达式或直接的 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)