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

StackOverflow https://stackoverflow.com/questions/15080143

  •  11-03-2022
  •  | 
  •  

문제

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top