Python 如何从键值对字典中检索前5个最大值(整数)?
我已经从一个函数中创建了3个字典,该函数遍历流行ios应用程序的数据帧。这3个字典根据键在数据帧中出现的频率包含键值对。从这些字典中,我想检索每个字典的5个最大值以及相应的键。这些是数据帧迭代的结果。显然,我可以手动看到这一点,但我希望python确定最大的5个Python 如何从键值对字典中检索前5个最大值(整数)?,python,sorting,dictionary,max,key-value,Python,Sorting,Dictionary,Max,Key Value,我已经从一个函数中创建了3个字典,该函数遍历流行ios应用程序的数据帧。这3个字典根据键在数据帧中出现的频率包含键值对。从这些字典中,我想检索每个字典的5个最大值以及相应的键。这些是数据帧迭代的结果。显然,我可以手动看到这一点,但我希望python确定最大的5个 Prices: {0.0: 415, 4.99: 10, 2.99: 13, 0.99: 31, 1.99: 13, 9.99: 1, 3.99: 2, 6.99: 3} Genres: {'Productivity': 9, 'Sho
Prices: {0.0: 415, 4.99: 10, 2.99: 13, 0.99: 31, 1.99: 13, 9.99: 1, 3.99: 2, 6.99: 3}
Genres: {'Productivity': 9, 'Shopping': 12, 'Reference': 3, 'Finance': 6, 'Music': 19, 'Games': 308, 'Travel': 6, 'Sports': 7, 'Health & Fitness': 8, 'Food & Drink': 4, 'Entertainment': 19, 'Photo & Video': 25, 'Social Networking': 21, 'Business': 4, 'Lifestyle': 4, 'Weather': 8, 'Navigation': 2, 'Book': 4, 'News': 2, 'Utilities': 12, 'Education': 5}
Content Ratings: {'4+': 304, '12+': 100, '9+': 54, '17+': 30}
您可以按值对字典进行排序,然后对前5个进行切片:
sorted(Prices, key=Prices.get, reverse=True)[:5]
其他两个dict也是如此。您也可以使用itemgetter来完成此操作
prices= {0.0: 415, 4.99: 10, 2.99: 13, 0.99: 31, 1.99: 13, 9.99: 1, 3.99: 2, 6.99: 3}
genres= {'Productivity': 9, 'Shopping': 12, 'Reference': 3, 'Finance': 6, 'Music': 19, 'Games': 308, 'Travel': 6, 'Sports': 7, 'Health & Fitness': 8, 'Food & Drink': 4, 'Entertainment': 19, 'Photo & Video': 25, 'Social Networking': 21, 'Business': 4, 'Lifestyle': 4, 'Weather': 8, 'Navigation': 2, 'Book': 4, 'News': 2, 'Utilities': 12, 'Education': 5}
contentRatings= {'4+': 304, '12+': 100, '9+': 54, '17+': 30}
arr = [prices,contentRatings,genres]
from operator import itemgetter
for test_dict in arr:
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# 5 largest values in dictionary
# Using sorted() + itemgetter() + items()
res = dict(sorted(test_dict.items(), key = itemgetter(1), reverse = True)[:5])
# printing result
print("The top 5 value pairs are " + str(res))
我很好奇,你介意分享创建这些字典的代码吗?