【问题标题】:How to retrieve the top-5 largest values (integers) from a dictionary of key-value pairs?如何从键值对字典中检索前 5 个最大值(整数)?
【发布时间】:2020-03-29 21:53:01
【问题描述】:

我从一个遍历流行 ios 应用程序的数据框的函数创建了 3 个字典。这 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}

【问题讨论】:

  • 我很好奇,你介意分享创建这些字典的代码吗?

标签: python sorting dictionary max key-value


【解决方案1】:

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

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

其他两个字典也一样。

【讨论】:

    【解决方案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)) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      相关资源
      最近更新 更多