-2

So i have this dictionary in (Python 3.x) :

dict = {
    "Gryffindor": gryffcount,
    "Ravenclaw": ravencount,
    "Hufflepuff": hufflecount,
    "Slytherin": slycount
}

gryffcount, ravencount, hufflecount and slycount are int variables.

And I want to output a list in which : - the first item should be the key for which the value is the highest - the second one should be the key for which the value is the second highest - and so on... EDIT : but if two counts are equal then the one that was mentioned first in the dictionary should appear first.

So if gryffcount == 0, ravencount == 2, hufflecount == 0, slycount == 4

I should get this list :

["Slytherin","Ravenclaw","Gryffindor","Hufflepuff"]
Michael
  • 63
  • 5
  • Assuming your dictionary is “dct”: sorted_keys = map(operator.itemgetter(0), sorted(dct.items(), key=operator.itemgetter(1))) – randomir Jan 14 '19 at 02:18
  • Did you mean `["Slytherin","Ravenclaw","Gryffindor","Hufflepuff"]`? – Mad Physicist Jan 14 '19 at 02:18
  • yes, and I fogot to add an additional condition. I just edited the question – Michael Jan 14 '19 at 02:37
  • Hi I took time to answer your [question](https://math.stackexchange.com/questions/3196310/fundamental-theorem-of-algebra-and-quaternions) don't delete it without showing you understood and render thanks – reuns Apr 21 '19 at 21:07

2 Answers2

5

This should do it

sorted(dict, key=dict.get, reverse=True)
BugCatcherJoe
  • 487
  • 3
  • 17
0

Renaming dict to my_data to avoid clashing with the builtin dict:

my_data = {
    "Gryffindor": gryffcount,
    "Ravenclaw": ravencount,
    "Hufflepuff": hufflecount,
    "Slytherin": slycount
}

# create a new dictionary, sorted by value
# For Python 3.6+ if you're using CPython, or any version of Python 3.7+
my_data_sorted_by_value = dict(sorted(my_data.items(), key=lambda t: t[1]))

# older Pythons:
import collections
my_data_sorted_by_value = collections.OrderedDict(sorted(my_data.items(), key=lambda t: t[1]))

# and here are the keys
print(list(my_data_sorted_by_value.keys()))
dtanabe
  • 1,611
  • 9
  • 18