简体   繁体   中英

Python - Order dictionary into a list of ascending order

I have the following sample code:

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

And what gets printed from the function is:

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']

And I don't quite know what's going on. I should be getting:

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

But my function consistently returns ['article1.txt', 'article3.txt', 'article2.txt'] , no matter if I change keywords.

Help would be much appreciated!

I think this is what you need:

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

Just an info: Articles is in the form of dict of dict. So you will always get unordered outputs. Try to use ordered dict for articles

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