プログラムには2つの問題があります
{}
作成したdictの代わりに空のdictを返します
- まだフィルター機能を組み込んでいません
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)