简体   繁体   中英

sorting key-value pairs in python

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?

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 )

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

您可以按以下值对字典进行排序:

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

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