0

Below is my code:

import heapq

sentences_scores = {'Fruit': 6, 'Apple': 5, 'Vegetables': 3, 'Cabbage': 9, 'Banana': 1}

summary = heapq.nlargest(3, sentences_scores, key = sentences_scores.get)

text = ""
for sentence in summary:
    text = text + sentence + ' '
print(text)

I get the output:

Cabbage Fruit Apple

But i want to get the output:

Fruit Apple Cabbage

How can i do that?

polm23
  • 14,456
  • 7
  • 35
  • 59
Maple
  • 179
  • 1
  • 1
  • 9

2 Answers2

2

First of all, your dictionary is not ordered, so you can't get the same order out; the order literally does not exist. As comments say, use OrderedDict instead.

Also, if you are working with fruit, don't name your variable sentences. :P

import heapq
from collections import OrderedDict

fruit_scores = OrderedDict([('Fruit', 6), ('Apple', 5), ('Vegetables', 3), ('Cabbage', 9), ('Banana', 1)])

best_fruit = heapq.nlargest(3, sentences_scores, key = sentences_scores.get)

best_fruit_scores = OrderedDict((fruit, score)
    for fruit, score in fruit_scores.items() if fruit in best_fruit)
# => OrderedDict([('Fruit', 6), ('Apple', 5), ('Cabbage', 9)])

best_fruit_names = [fruit
    for fruit in fruit_scores if fruit in best_fruit]
# => ['Fruit', 'Apple', 'Cabbage']
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

nlargest returns a sorted list

Equivalent to: sorted(iterable, key=key, reverse=True)[:n]

To get the list in the original order you can iterate over the dict to find the elements in the results

original_order = [key for key in sentences_scores.keys() if key in summary] # ['Fruit', 'Apple', 'Cabbage']
Guy
  • 46,488
  • 10
  • 44
  • 88
  • 2
    @Amadan Python 3.6 and newer [maintains dict insertion order](https://stackoverflow.com/a/39537308/5168011). – Guy Dec 18 '19 at 07:27