How to get the highest key from dictionary (python)?

422 views Asked by At

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

3

There are 3 answers

0
alexisdevarennes On BEST ANSWER

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
2
yinnonsanders On

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.

0
Eric Duminil On

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'