Search code examples
pythondictionarytuplesmax

Get max key value pair from dictionary, but with key restrictions


Imagine I have a dictionary like this:

{(0,0) : 5 , (0,1) : 7 , (0,2) : 9 , (1,0) : 1 , (1,1) : 3 , (1,2) : 20 , (2,0) : 6 , (2,1) : 5 , (2,2) : 25 }

Is there a way to get the max key value pair, but with only taking into account keys with certain values?

For example, if I wanted the max pair from when the first index of the key is 0. So the max between:

 {(0,0) : 5 , (0,1) : 7 , (0,2) : 9}

Which would be (0,2) : 9


Solution

  • You can use a comprehension with an if clause to get all the relevant elements, and then get the max value with max():

    max(value for key, value in d.items() if key[0] == 0)
    

    A more general case would be something like:

    max(value for key, value in d.items() if predicate(key, value))
    

    Where predicate is some function which returns a boolean.

    For getting both the key and value, you can use the following:

    d = {(0,0) : 5 , (0,1) : 7 , (0,2) : 9 , (1,0) : 1 , (1,1) : 3 , (1,2) : 20 , (2,0) : 6 , (2,1) : 5 , (2,2) : 25 }
    max_key = max({k: v for k, v in d.items() if k[0] == 0}, key=d.get)
    max_value = d[max_key]
    

    Note that there may be several keys with the max value.