Python - 将字典排序为升序列表

时间:2017-04-13 04:17:34

标签: python python-2.7

我有以下示例代码:

articles = {'article1.txt': {'harry': 3, 'hermione': 2, 'ron': 1},
 'article2.txt': {'dumbledore': 5, 'hermione': 3},
 'article3.txt': {'harry': 5, 'hermione': 5}}
keywords = ['hermione', 'dumbledore']

def recommend_articles(articles, keywords):

    def max_count(key): 
      result = 0 
      for names in articles.keys():
        for name, count in articles[names].items():
          if name in keywords:
            result += count
            print name, count, result
      return result

    article_list = sorted(articles.keys(), key=max_count, reverse = True)
    print article_list

从函数中打印出来的是:

hermione 2 2
hermione 5 7
dumbledore 5 12
hermione 3 15
hermione 2 2
hermione 5 7
dumbledore 5 12
hermione 3 15
hermione 2 2
hermione 5 7
dumbledore 5 12
hermione 3 15
['article1.txt', 'article3.txt', 'article2.txt']

而且我不太清楚发生了什么。我应该得到:

>>>recommended_articles(articles, keywords)
['article2.txt', 'article3.txt', 'article1.txt']

但无论我是否更改关键字,我的功能都会一直返回['article1.txt', 'article3.txt', 'article2.txt']

非常感谢帮助!

2 个答案:

答案 0 :(得分:0)

我认为这就是你所需要的:

articles = {'article1.txt': {'harry': 3, 'hermione': 2, 'ron': 1},
 'article2.txt': {'dumbledore': 5, 'hermione': 3},
 'article3.txt': {'harry': 5, 'hermione': 5}}
keywords = ['hermione', 'dumbledore']

def recommend_articles(articles, keywords):

    def max_count(key): 
      result = 0 
      for name in articles[key].keys():
        if name in keywords:
          result = result + articles[key][name]
      return result

    article_list = sorted(articles.keys(), key=max_count, reverse = True)
    print article_list

print(recommend_articles(articles, keywords))

答案 1 :(得分:0)

只是一个信息:文章是dict的dict形式。因此,您将始终获得无序输出。尝试使用有序的dict文章