从Python的大字典中获取前3个最高值的快速有效的方法是什么?

jtw3ybtb  于 2023-01-16  发布在  Python
关注(0)|答案(2)|浏览(174)

我已经花了几个小时来检查字典,并得到三个最大值的键以显示在输出中。
下面是一个例子:

dict1 = {
    "a": 5,
    "b": 1,
    "c": 20,
    "d": 15,
    "e": 100,
    "f": 75
}

我想解析出三个最高的值,并将它们表示为:

'e' has a value of 100
'f' has a value of 75
'c' has a value of 20

所以应该是键值对,而不仅仅是值。
我试过这样的东西,但似乎一点也不方便。

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

我相信有一个非常简单的方法就在我眼皮底下。谢谢。

hzbexzde

hzbexzde1#

标准库Counter类可以快速完成您要做的事情:

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}")

输出:

e has a value of 100
f has a value of 75
c has a value of 20
pbpqsu0x

pbpqsu0x2#

尝试对字典项进行排序并打印前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}")

图纸:

'e' has a value of 100
'f' has a value of 75
'c' has a value of 20

相关问题