Reputation: 51
Input is: book_shop = {'sci fi': 12, 'mystery': 15, 'horror': 8, 'mythology': 10, 'young_adult': 4, 'adventure':14}
Output has to be: The highest selling book genre is mystery and the number of books sold are 15
Need to solve this without using max function.
I've tried this:
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)
Output came: The highest selling book genre is adventure and the number of books sold are 0
What to do?
Upvotes: 0
Views: 73
Reputation: 3770
You can get the key with max value using :
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))
Updated your code to get max value without max function. Basically you should compare the largest value with the value for that specific key.
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)
Upvotes: 1