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?

2
  • 2
    @Chris I think he wants to sort by the order in the dictionary Commented Dec 18, 2019 at 7:09
  • @U10-Forward-ReinstateMonica Ah i get it. Thx :). So its an OrderedDict question Commented Dec 18, 2019 at 7:10

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@Amadan Python 3.6 and newer maintains dict insertion order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.