首页 文章资讯内容详情

Python程序在字典中查找最高的3个值

2026-06-04 1 花语

在本文中,我们将学习解决给定问题陈述的解决方案和方法。

问题陈述

给定字典,我们需要找到三个最高值并显示它们。

方法1-使用收集模块(计数器功能)

示例

from collections import Counter # Initial Dictionary my_dict = {t: 3, u: 4, t: 6, o: 5, r: 21} k = Counter(my_dict) # Finding 3 highest values high = k.most_common(3) print("Dictionary with 3 highest values:") print("Keys: Values") for i in high: print(i[0]," :",i[1]," ")

输出结果

Dictionary with 3 highest values: Keys: Values r : 21 t : 6 o : 5

方法2-使用heapq模块(最大功能)

示例

from collections import Counter # Initial Dictionary my_dict = {t: 3, u: 4, t: 6, o: 5, r: 21} k = Counter(my_dict) # Finding 3 highest values high = k.most_common(3) print("Dictionary with 3 highest values:") print("Keys: Values") for i in high: print(i[0]," :",i[1]," ")

输出结果

Dictionary with 3 highest values: Keys: Values r : 21 t : 6 o : 5

结论

在本文中,我们了解了将十进制数转换为二进制数的方法。