-2
my_list = [{0: 0}, {1: 4.2}, {2: 3.7}, {3: 5.0}, {4: 4.0}, {5: 3.3}, {6: 4.3}, {7: 4.0}, {8: 3.9}, 0, {10: 4.0}]

What I want my program to do is go through the list, record the highest value (as in the value from a key-value pair) once it's scanned through the entire thing, append that key-pair value to a new list, remove that key-pair value from the original list [my_list], and repeat the process twice more. So the desired output would look like this:

desired output: [{3: 5.0},{6: 4.3},{1: 4.2}]

I'm not sure how to achieve the desired output.

user132520
  • 151
  • 1
  • 1
  • 5
  • Looks like a valid algorithm, so what's your problem doing it ? – polku May 25 '16 at 11:59
  • It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask]. – Łukasz Rogalski May 25 '16 at 12:00
  • You have a non-dictionary element in your list. – Selcuk May 25 '16 at 12:02

1 Answers1

0

I'm assuming that the single integer in your my_list is a typo.

Use the heapq module to get the three largest items. This has slightly better complexity and memory efficiency than sorting the whole list and then extracting the last three elements.

>>> from heapq import nlargest
>>> my_list = [{0: 0}, {1: 4.2}, {2: 3.7}, {3: 5.0}, {4: 4.0}, {5: 3.3}, {6: 4.3}, {7: 4.0}, {8: 3.9}, {10: 4.0}]
>>> nlargest(3, my_list, key=lambda d: d.values()[0])
[{3: 5.0}, {6: 4.3}, {1: 4.2}]

The key function specifies the criterion by which the items from your list are to be ordered, it simply fetches the only value any individual dictionary has.

Community
  • 1
  • 1
timgeb
  • 76,762
  • 20
  • 123
  • 145