首页 > 解决方案 > 以下字典 python 3.8 中的最大值及其键

问题描述

输入是:book_shop = {'sci fi': 12, 'mystery': 15, 'horror': 8, 'mythology': 10, 'young_adult': 4, 'adventure':14}

输出必须是:The highest selling book genre is mystery and the number of books sold are 15

需要在不使用 max 函数的情况下解决这个问题。

我试过这个:

book_shop = {'sci fi': 12, 'mystery': 15, 'horror': 8, 'mythology': 10, 'young_adult': 4, 'adventure':14}
largest = 0

for key, value in book_shop.items():
    if largest in book_shop.values():
        largest = book_shop.values()
        key = book_shop.keys()
        
print("The highest selling book genre is ", key, " and the number of books sold are ", largest)

输出来了:The highest selling book genre is adventure and the number of books sold are 0

该怎么办?

标签: python-3.x

解决方案


您可以使用以下方法获取具有最大值的密钥:

max_key = max(book_shop,key=book_shop.get)

print("The highest selling book genre is ", max_key, " and the no of books sold are ",book_shop.get(max_key))


更新了您的代码以在没有 max 函数的情况下获得最大值。基本上,您应该将最大值与该特定键的值进行比较。

In [193]: book_shop = {'sci fi': 12, 'mystery': 15, 'horror': 8, 'mythology': 10, 'young_adult': 4, 'adventure':14} 
     ...: largest = 0 
     ...: key1= "" 
     ...: for key, value in book_shop.items(): 
     ...:     #print("key ",key," value ",value) 
     ...:     if largest < int(book_shop.get(key)): 
     ...:         #print(True) 
     ...:         largest = value 
     ...:         key1 = key 
     ...:          
     ...: print("The highest selling book genre is ", key1, " and the number of books sold are ", largest)   


推荐阅读