从字典中提取最小 x 值键

Jar*_*use 4 python dictionary

假设我们希望像这样从字典中提取最小值

scores = {
    0:1.3399288498085087,
    1:1.2672683347433629,
    3:1.6999159970296505, 
    4:1.8410942584597279,
    5:1.336658057628646
}

#find minimum value in dictionary
minimum_value = min(scores.values())

#get keys with minimal value using list comprehension
minimum_keys = [key for key in scores if scores[key]==minimum_value]

minimum_keys
Run Code Online (Sandbox Code Playgroud)

这将返回具有最低值的键。但是,如果我想提取最少 2 个键并将它们放入列表中怎么办?如果我想要最少 20 个怎么办?对于任意数量的所需最小值,我将如何做到这一点?

Gri*_*mar 5

事实上,问题比你想象的要简单:

scores = {
    0:1.3399288498085087,
    1:1.2672683347433629,
    3:1.6999159970296505, 
    4:1.8410942584597279,
    5:1.336658057628646
}

# minimum key
print(min(scores, key=scores.get))

# n minimum keys
print(sorted(scores, key=scores.get)[:3])
Run Code Online (Sandbox Code Playgroud)

输出:

1
[1, 5, 0]
Run Code Online (Sandbox Code Playgroud)

两者minsorted允许您提供一个key要使用值调用的函数,以计算用于排序的关联值。通过提供scores.get该函数,您可以按匹配值对键进行排序,这就是您想要的。