Maple
Maple

Reputation: 179

Python: Order of output from a set

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?

Upvotes: 0

Views: 86

Answers (2)

Guy
Guy

Reputation: 50809

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

Upvotes: 0

Amadan
Amadan

Reputation: 198294

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

Upvotes: 2

Related Questions