Search code examples
pythonpython-3.xdictionarymaxpython-2.x

How to get the maximum value of a dictionary tuple


I have a dictionary like this:

dic={(0, 1): 0.059999999999999996,
 (0, 5): 0.13157894736842105,
 (0, 15): 0.23157894736842105,
 (1, 0): 0.049999999999999996,
 (5, 0): 0.13157894736842105,
 (5, 15): 0.049999999999999996,
 (15, 5): 0.23157894736842105}

I would like to get the maximum value for each element in the first coordinate of the vector and also the second element of the vector.

The output would be:
For 0 [First coordinate]:      (0, 5): 0.13157894736842105
For 0 [Second coordinate]:      (5, 0): 0.13157894736842105
For 1 [First coordinate]:       (1,0) 0.049999999999999996
For 1 [Second coordinate]:       (0,1) 0.059999999999999996
and so on.

I know that I can use something like this

max_keys = [k for k, v in dic.items() if v == max_value] 

but I am not able to get the correct way.


Solution

  • This can be done in a oneliner

    For example, for 0 [First coordinate]:

    print(max([(k, v) for k, v in filter(lambda x: x[0][0]==y, dic.items())], key=lambda x:x[1]))
    Out[2]: ((0, 15), 0.23157894736842105)
    

    But better is to put this into a function:

    def get_max(dic, coord, val):
        return max(filter(lambda item: item[0][coord] == val, dic.items()), key=lambda x: x[1])
    

    For 0 [First coordinate]:

    print(get_max(dic, 0, 0))
    Out[5]:  ((0, 5), 0.23157894736842105)
    # or storing the key and the value:
    key_max, value_max = get_max(dic, 0, 0)
    

    For 0 [Second coordinate]:

    print(get_max(dic, 1, 0))
    Out[6]: ((5, 0), 0.13157894736842105)
    

    and so on...

    Hope that helped and happy coding!