0
Python Dictionary
I have a dictionary {1:2, 2:2, 3:3, 4:3, 5:1}. I want to retrieve the smallest key with maximum value. As clear from the dictionary, maximum value is 3 for both keys 3 and 4. But out of keys 3 and 4 the minimum is 3, so how can I retrieve this 3 from the dictionary and return it from the function ?
9 Antworten
+ 3
a={1:2, 2:2, 3:3, 4:3, 5:1}
b=[]
for i in a.keys():
if a[i]==max(a.values()):
b.append(i)
print(min(b))
+ 3
Abhay
highlander principle:
There can only be one!
😁
+ 3
It is a shortcut of Abhay s solution:
k, v of d. items() returns keys and values.
We need min k of all k which have v as max of d.values()
If you are not familiar with this "tricks" pleas choose the other solutions.
This one is than for another day.
+ 2
Neeraj Jain done
+ 1
Oma Falk it's returning 4 , my desired output is 3
0
Thanks Oma Falk ... please explain me your code briefly.
0
Abhay code works for your question, you need to put your code in to your discussion or we won't be able to see the issue and help.
0
Andrew Mehrle I think you mistakenly tagged me?