user256107
user256107

Reputation: 25

Python Function of a Dictionary

I have a small homework problem, getting my Python function to return the correct values.

Assignment:

Here is an example dictionary:

word_freq = {'the': 58, 'people': 6, 'beautiful': 8, 'cats': 13}

Write a function that takes as parameters: a word frequency dictionary and a threshold number with is an integer. This function should return a result that is a list of all the words whose frequency is greater than the threshold.

For example, suppose that you name your function top_words. If you call the function with the dictionary above and the threshold of 10:

top_words(word_freq, 10) you should get the result [‘the’, ‘cats’]

My code:

def frequencylist(frequentwords, threshold):
    for keys in frequentwords:
        if key > threshold:
            print(keys)

Test run:

frequentwords= {'hello':30, 'yellow':4, 'red':10, 'blue':35, 'orange':100}
frequencylist(frequentwords, 10)

... and I get this error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in frequencylist
TypeError: unorderable types: str() > int()

Upvotes: 1

Views: 496

Answers (3)

Alex
Alex

Reputation: 21766

You can just do this:

print [k for k,v in word_freq.items() if v>=10]

It would look like this in a method:

def frequencylist(frequentwords, threshold):
    return [k for k,v in word_freq.items() if v>=threshold]

Upvotes: 1

Garrett R
Garrett R

Reputation: 2662

Your functions is not quite right. When you iterate (loop) over the dictionary, you are only accessing the key values. You need to use the built-in iteritems() or items() functions to get both the key and the value.

   def above_thresh(someDict, thresh):
        return [field for field, value in someDict.iteritems() if value > thresh] 

In [6]: above_thresh(frequentwords, 10)
Out[6]: ['blue', 'orange', 'hello']

Alternatively, you can fix your approach like this:

def frequencylist(frequentwords, threshold):
   toRet = [] 
   for keys in frequentwords: 
        if frequentWords[key] > threshold:
              toRet.append(key)
   return toRet   

Upvotes: 1

Prune
Prune

Reputation: 77827

The keys are words; your threshold is an integer. You can't compare those types with >. I think you mean to compare the value:

for key, value in frequentwords.items():
  if value > threshold:
    print(key)

This yields the desired output:

blue
orange
hello

If you also want red, you need to change the comparison to >=

Upvotes: 2

Related Questions