Reputation: 85
I'm new to Python and I am having a small problem I want to solve
a={"1" : 3, "2" : 3, "6":3}
I have this dic and I would like to get the maximum key out of him for example in the dictionary above I would like to get the key 6 as a value
Upvotes: 2
Views: 414
Reputation: 54213
If you want the original key (as as string, not an integer), you could simply use max
with int
as key argument:
a = {"1" : 3, "2" : 3, "6":3}
max(a, key=int)
# '6'
Upvotes: 1
Reputation: 1871
For a simple, functional approach:
max(map(int,a))
This applies the int
function to each key of a
using map
to convert the keys as strings to integers, then finds the maximum of these using max
.
Upvotes: 2
Reputation: 5632
There are many ways, one way of doing it is:
greatest = max(int(k) for k in a)
Or a human readable format, so you can understand the logic:
greatest = None
for k in a:
k = int(k)
if greatest == None:
greatest = k
if k > greatest:
greatest = k
Upvotes: 3