简体   繁体   English

如何获取字典中的第一个K最小数字

[英]how to get first K smallest number in a dictionary

For example, I have a dictionary例如,我有一本字典

dicts["A"] = 1
dicts["B"] = 2
dicts["C"] = 3 # .....etc, 

if I want to get the first 2 key, ie "A" and "B" based on their values, ie 1 and 2, what should I do?如果我想根据它们的值(即 1 和 2)获取前 2 个键,即"A""B" ,我该怎么办? Thanks in advance.提前致谢。

Try:尝试:

#lets say
dic={'A':2,'B':1, 'C':5}
#sorting the dict
dic = {k: v for k, v in sorted(dic.items(), key=lambda item: item[1])}

Now that the dictionary is sorted, iterate through it.现在字典已经排序,遍历它。 To find K smallest Values:要找到 K 个最小值:

k = K
for i in range(k):
    print([k[0] for k in dic.items()][i])

Therefore, shortly:因此,很快:

k = K
for i in range(k):
    print([k[0] for k in {k: v for k, v in sorted(dic.items(), key=lambda item: item[1])}.items()][i])

As a One-Liner:作为单线:

k = K
dic={'A':2,'B':1, 'C':5}
print('\n'.join([k[0] for k in {k: v for k, v in sorted(dic.items(), key=lambda item: item[1])}.items()][i] for i in range(k)))
dic={'A':1,'B':2, 'C': 3}
k = 2
[y[0] for y in sorted(dic.items(), key = lambda x: x[1])[:k]]

The last line sort the dictionary items according to the key ( x[1] ), then take the first k items ( [:k] ) and then extract only the keys ( y[0] ).最后一行根据键( x[1] )对字典项进行排序,然后取前k个项( [:k] ),然后仅提取键( y[0] )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何以我在第一行中获得最大数字、在第二行中获得最小数字、在第三行中获得第二大数字的方式对组进行排序,依此类推 - How to sort a group in a way that I get the largest number in the first row and smallest in the second and the second largest in the third and so on 如何获得排序列表中最大和最小的数字? - How to get largest and smallest number in a sorted list? 如何获得一个字典的多个最小/最大值? - How to get more than one smallest /largest values of a dictionary? 如何在python Ndarray中获取前5个最小值并获取它们在ndarray中的位置 - How to get the first smallest 5 values in a python Ndarray and get their position in the ndarray 如何获取列表中从最大到最小的索引? - How do I get the indexes from the biggest to smallest number in a list? 获取字典中 5 个最小值对应的键 - Get the keys corresponding to the 5 smallest values within a dictionary Python算法在未排序的数组中找到k个最小数字的索引? - Python algorithm to find the indexes of the k smallest number in an unsorted array? 两个排序数组并找到第 k 个最小的数字 - two sorted array and find k'th smallest number 具有最大长度 m 和公差 k 的子列表的最小数量 - smallest number of sublists with maximum length m and tolerance k 算法(Python):找到大于k的最小数 - Algorithm (Python): find the smallest number greater than k
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM