How to find the (n) keys with the highest values in a dictionary and store these in a set?

Question:

I would like to know how it is possible to extract the 4 keys from a dictionary with the highest values, and store these as a set. My dictionary looks like this:
my_dict = {Suzanne: 6, Peter: 9, Henry: 2, Paula: 275, Fritz: 1, Anita: 80}.
(The desired output in this case would be the set my_set = {Paula, Anita, Peter, Suzanne}

I sorted out the highest values present in the dictionary, using the command

sorted(my_dict, key=my_dict.get, reverse=True)[:4].

What would be the command to create a set containing these four keys?

Answers:

What would be the command to create a set containing these four keys?

Use set to convert list returned by sorted into set, that is

my_dict = {"Suzanne": 6, "Peter": 9, "Henry": 2, "Paula": 275, "Fritz": 1, "Anita": 80}
top = set(sorted(my_dict, key=my_dict.get, reverse=True)[:4])
print(top)

gives output

{'Paula', 'Suzanne', 'Anita', 'Peter'}
Answered By: Daweo

Just make a set from the list returned from sorted(). Note that there’s no need to reverse the sort order because you can get the highest 4 elements with a different slice as follows:

my_dict = {"Suzanne": 6, "Peter": 9, "Henry": 2, "Paula": 275, "Fritz": 1, "Anita": 80}
top = set(sorted(my_dict, key=my_dict.get)[-4:])
print(top)
Answered By: Fred
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.