I have to find the maximum value in a dictionary called fav_num
:
fav_num = {
"Ian": 3.14,
"Tobiloba": 5,
"Kaden": 10,
"Sophie": 18,
"Aarav": 17,
"Zach": 6,
"Ewen": 64,
"Nirvana": 25,
"Arjun": 3.14,
"Olivia": 7,
}
max = 0
for value in fav_num:
if fav_num[value] > max:
max = value
print(max)
I have to use a loop, so I set max is equal to 0 and for each value, it compares it with the previous value. It is giving me this error:
'>' not supported between instances of 'int' and 'str'
Does fav_num[value] not print the corresponding value of the key?
CodePudding user response:
Use the max()
function with the key
parameter to get the key corresponding to the maximum value:
max(fav_num, key=fav_num.get)
If you must use a for
loop, you can keep track of the maximum value and the key corresponding to that value:
result = None
max_value = float('-inf')
for key, value in fav_num.items():
if value > max_value:
result = key
max_value = value
print(result)
These output:
Ewen
CodePudding user response:
You need to use different methods to find the key with values in the dict.
The solution I'm offering is simply to compare the greatest value with the greatest value in the value of the Dictionary.
fav_num = {
"Ian": 3.14,
"Tobiloba": 5,
"Kaden": 10,
"Sophie": 18,
"Aarav": 17,
"Zach": 6,
"Ewen": 64,
"Nirvana": 25,
"Arjun": 3.14,
"Olivia": 7,
for k, v in fav_num.items():
if v==max(fav_num.values()):
print(k)
result
Ewen
or
Python can use indexes to keep the Dictionary in order.
It's cumbersome, but there are the following ways .
find index
max_ = list(fav_num.values()).index(max(fav_num.values()))
2.Finding Values Using Indexes
list(fav_num.keys())[max_]
result
Ewen
CodePudding user response:
Method 1 : Iterate over items
You can iterate over each item value pair of dictionary and find the maximum and return it
for name, value in fav_num.items():
if value == max(fav_num.values()):
print(name, value)
Method 2 : One-Liner
You can find the maximum in list of values and then get the corresponding key for it
list(fav_num.keys())[list(fav_num.values()).index(max(fav_num.values()))]
You can visit this page on more info for dictionary functions : Python Dictionary Methods
One-Liner code was inspired from this page : One liner to get keys from values