Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading