I'm given a .tsv file called "population.tsv", which tells the populations of many cities. I have to create a dictionary with the cities being the key and the populations being its values. After creating the dictionary, I have to eliminate the cities which have less than 10,000 people. Whats wrong?
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)
There are two issues with your program
{}
instead of the dict you created I have to eliminate the cities which have less than 10,000 people.
The fixed code
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)
Note you could also use the dict
built-in by passing a generator expression or straightforward dict comprehension (If using 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.