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 ?

11th Jul 2020, 8:12 PM
Neeraj Jain
Neeraj Jain - avatar
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))
11th Jul 2020, 8:25 PM
Abhay
Abhay - avatar
+ 3
Abhay highlander principle: There can only be one! 😁
11th Jul 2020, 8:27 PM
Oma Falk
Oma Falk - avatar
+ 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.
11th Jul 2020, 8:36 PM
Oma Falk
Oma Falk - avatar
11th Jul 2020, 8:24 PM
Oma Falk
Oma Falk - avatar
+ 2
11th Jul 2020, 8:28 PM
Oma Falk
Oma Falk - avatar
+ 1
Oma Falk it's returning 4 , my desired output is 3
11th Jul 2020, 8:27 PM
Neeraj Jain
Neeraj Jain - avatar
0
Thanks Oma Falk ... please explain me your code briefly.
11th Jul 2020, 8:30 PM
Neeraj Jain
Neeraj Jain - avatar
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.
11th Jul 2020, 10:24 PM
Andrew Mehrle
Andrew Mehrle - avatar
0
Andrew Mehrle I think you mistakenly tagged me?
11th Jul 2020, 11:18 PM
Abhay
Abhay - avatar