从字典中提取最小x值键



假设我们希望从字典中提取最小值,如下所示

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

返回值最小的键。然而,如果我想提取最小的2个键并将它们放入列表中该怎么办?如果我想要最少20呢?对于任意数量的最小值我该怎么做呢?

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

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

输出:

1
[1, 5, 0]

minsorted都允许你提供一个key,它是一个函数,可以用一个值来调用,来计算一个相关的值,用于排序。通过提供scores.get作为该函数,您可以根据键的匹配值对键进行排序,这正是您想要的。

解决方法如下:

# your dictionary
scores = {
0:1.3399288498085087,
1:1.2672683347433629,
3:1.6999159970296505, 
4:1.8410942584597279,
5:1.336658057628646
}
# a list to store keys
min_keys = []
# how many minimum keys you need
count = 2
# iterate over dict items, sorted based on values 
for key,val in sorted(scores.items(), key=lambda x:x[1])[:count]:
min_keys.append(key)

print(min_keys)
# prints [1,5]

相关内容

  • 没有找到相关文章

最新更新