简体   繁体   中英

Creating a Dictionary through .tsv file and Eliminating Keys in which Values are below a certain number

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

  1. It returns an empty dict {} instead of the dict you created
  2. You have still not incorporated the filter function I have to eliminate the cities which have less than 10,000 people.
  3. You shouldn't name a variable to a built-in

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM