简体   繁体   中英

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

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM