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