Python 程式用於在詞典中找到最高 3 個值
在本文中,我們將瞭解解決方案和方法來解決給定的問題陳述。
問題陳述
給定一個詞典,我們需要找出三個最高值並展示出來。
方法 1 − 使用 collection 模組(計數器函式)
示例
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 模組(nlargest 函式)
示例
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
結論
在本文中,我們學習了將十進位制數轉換為二進位制數的方法。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP