[英]What would be a quick and effective way to get top 3 highest values from a large dictionary in Python?
I've been trying for several hours to go through a dictionary and get three highest-value keys to be presented in the output.我已经尝试了几个小时,通过字典找到 go,并获得了三个最高值的键,以显示在 output 中。
So here's an example dictionary:所以这是一个示例字典:
dict1 = {
"a": 5,
"b": 1,
"c": 20,
"d": 15,
"e": 100,
"f": 75
}
And I want to parse out the three highest values and present them something like this:我想解析出三个最高值并像这样呈现它们:
'e' has a value of 100
'f' has a value of 75
'c' has a value of 20
So it should be key-value pairs, not just the values.所以它应该是键值对,而不仅仅是值。
I tried something like this but it didn't seem convenient at all.我试过这样的东西,但它似乎一点也不方便。
v = list(dict1.values())
k = list(dict1.keys())
print(f"{k[v.index(max(v))]} has a value of {max(v)}.")
# and so forth. not to mention this is only the one highest value, I need three
I'm sure there's a really simple way right under my nose.我敢肯定,就在我眼皮底下有一种非常简单的方法。 Thank you.
谢谢你。
The standard library Counter
class can make short work of what you are trying to do:标准库
Counter
class 可以简化您要执行的操作:
from collections import Counter
dict1 = {
"a": 5,
"b": 1,
"c": 20,
"d": 15,
"e": 100,
"f": 75
}
for k, v in Counter(dict1).most_common(3):
print(f"{k} has a value of {v}")
Output: Output:
e has a value of 100
f has a value of 75
c has a value of 20
Try to sort the dictionary items and print first 3 items:尝试对字典项目进行排序并打印前 3 个项目:
dict1 = {"a": 5, "b": 1, "c": 20, "d": 15, "e": 100, "f": 75}
for k, v in sorted(dict1.items(), key=lambda k: k[1], reverse=True)[:3]:
print(f"'{k}' has a value of {v}")
Prints:印刷:
'e' has a value of 100
'f' has a value of 75
'c' has a value of 20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.