如何从键值对字典中检索前5个最大值(整数)?

2024-06-25 22:51:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经从一个函数中创建了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, '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}

Tags: 数据函数应用程序字典music手动productivity频率
2条回答

您还可以使用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)) 

您可以按值对词典进行排序,然后将前5个值切片:

sorted(Prices, key=Prices.get, reverse=True)[:5]

其他两个都一样

相关问题 更多 >