[英]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.我想知道如何从具有最高值的字典中提取 4 个键,并将它们存储为一个集合。 My dictionary looks like this: my_dict = {Suzanne: 6, Peter: 9, Henry: 2, Paula: 275, Fritz: 1, Anita: 80}.
我的字典是这样的: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}
(在这种情况下,所需的输出是集合 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].排序(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使用
set
将sorted
返回的list
转换为set
,即
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() .只需从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:
请注意,不需要颠倒排序顺序,因为您可以获得具有不同切片的最高 4 个元素,如下所示:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.