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

📅  最后修改于: 2022-05-13 01:55:07.156000             🧑  作者: Mango

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

Python中的字典是数据值的无序集合,用于像地图一样存储数据值,与其他仅将单个值作为元素保存的数据类型不同,字典包含键:值对。

例子:

Input : my_dict = {'A': 67, 'B': 23, 'C': 45,
                   'D': 56, 'E': 12, 'F': 69} 

Output : {'F': 69, 'A': 67, 'D': 56}

让我们看看我们可以在字典中找到最高 3 个值的不同方法。方法 #1:使用 collections.Counter()
Counter是用于计算可散列对象的 dict 子类。它是一个无序集合,其中元素存储为字典键,它们的计数存储为字典值。计数可以是任何整数值,包括零计数或负计数。 Counter 类类似于其他语言中的 bag 或 multisets。
most_common([n]) 返回n 个最常见元素的列表及其从最常见到最少的计数。

Python3
# Python program to demonstrate
# finding 3 highest values in a Dictionary
 
from collections import Counter
 
# Initial Dictionary
my_dict = {'A': 67, 'B': 23, 'C': 45,
           'D': 56, 'E': 12, 'F': 69}
 
k = Counter(my_dict)
 
# Finding 3 highest values
high = k.most_common(3)
 
print("Initial Dictionary:")
print(my_dict, "\n")
 
 
print("Dictionary with 3 highest values:")
print("Keys: Values")
 
for i in high:
    print(i[0]," :",i[1]," ")


Python3
# Python program to demonstrate
# finding 3 highest values in a Dictionary
from heapq import nlargest
 
# Initial Dictionary
my_dict = {'A': 67, 'B': 23, 'C': 45,
           'D': 56, 'E': 12, 'F': 69}
 
print("Initial Dictionary:")
print(my_dict, "\n")
 
ThreeHighest = nlargest(3, my_dict, key = my_dict.get)
 
print("Dictionary with 3 highest values:")
print("Keys: Values")
 
for val in ThreeHighest:
    print(val, ":", my_dict.get(val))


输出:
Initial Dictionary:
{'C': 45, 'B': 23, 'D': 56, 'A': 67, 'E': 12, 'F': 69} 

Dictionary with 3 highest values:
Keys: Values
F  : 69  
A  : 67  
D  : 56

方法 #2:使用 heapq.nlargest()

Python3

# Python program to demonstrate
# finding 3 highest values in a Dictionary
from heapq import nlargest
 
# Initial Dictionary
my_dict = {'A': 67, 'B': 23, 'C': 45,
           'D': 56, 'E': 12, 'F': 69}
 
print("Initial Dictionary:")
print(my_dict, "\n")
 
ThreeHighest = nlargest(3, my_dict, key = my_dict.get)
 
print("Dictionary with 3 highest values:")
print("Keys: Values")
 
for val in ThreeHighest:
    print(val, ":", my_dict.get(val))
输出:
Initial Dictionary:
{'D': 56, 'E': 12, 'F': 69, 'C': 45, 'B': 23, 'A': 67} 

Dictionary with 3 highest values:
Keys: Values
F : 69
A : 67
D : 56