在python中对键值对进行排序

时间:2016-07-10 15:21:48

标签: python sorting keyvaluepair

我正在制作一个如下所示的小程序

"""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()

我只是想对键值对进行排序。我有以下问题:

  1. 在上面的程序中,当我打印两个排序列表的合并时,它只显示未排序的合并
  2. 如何通过python函数获取已排序的键值对我正在使用它的当前fxn将返回键或值。我们能以某种方式得到它们吗?

3 个答案:

答案 0 :(得分:3)

根据顶部的注释,您希望返回键/值元组的列表。因此,您希望按值

对字典的进行排序
sorted(temp.items(), key=itemgetter(1), reverse=True)

请注意,您分别对键和值进行排序的策略不起作用 - 您最终会将键与不属于一起的值进行匹配。

另请注意,collections.Counter已针对完成此任务进行了优化(请参阅.most_common

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

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