0

I am working on a small program as written below

"""Count words."""
    # TODO: Count the number of occurences of each word in s

    # TODO: Sort the occurences in descending order (alphabetically in case of ties)

    # TODO: Return the top n words as a list of tuples (<word>, <count>)    
from operator import itemgetter

def count_words(s, n):
    """Return the n most frequently occuring words in s."""

    t1=[]
    t2=[]
    temp={}
    top_n={}
    words=s.split()
    for word in words:
        if word not in temp:
            t1.append(word)
            temp[word]=1
        else:
            temp[word]+=1

    t1 = sorted(temp,key=temp.get,reverse=True) # to get sorted keys
    t2 = sorted(temp.values(),reverse=True) # to get sorted values
    top_n = dict(zip(t1,t2))
    print top_n

    return 


def test_run():
    """Test count_words() with some inputs."""
    count_words("cat bat mat cat bat cat", 3)
    count_words("betty bought a bit of butter but the butter was bitter", 3)


if __name__ == '__main__':
    test_run()

I am just trying to sort the key-value pair. I have below questions :

  1. In the above program when I print merge of two sorted list its showing me only the unsorted merger
  2. How to get the sorted key value pair by python function the current fxn which I am using it wither returns the keys or values. Can we get both somehow?
1
  • Did you look into collections.Counter? You could also consider collections.defaultdict to get rid of your if statement. defaultdict(0) will create a dictionary which uses 0 as the default value for unknown keys. Commented Jul 10, 2016 at 15:28

3 Answers 3

3

According to the comment at the top, you want to return a list of tuples of key/value. As such, you want to sort the dictionary's items by the value:

sorted(temp.items(), key=itemgetter(1), reverse=True)

Note that your strategy of sorting the keys and the values separately won't work -- You'll end up matching up keys with values that don't belong together.

Also note that there is collections.Counter which is optimized for doing exactly this task (see .most_common)

Sign up to request clarification or add additional context in comments.

Comments

2
sorted([(value,key) for (key,value) in temp.items()])

Comments

1

You can sort dictionary by the value like this:

sorted(temp.items(), key = lambda x: x[1], reverse = True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.