Home > database >  Get max key value pair from dictionary, but with key restrictions
Get max key value pair from dictionary, but with key restrictions

Time:08-12

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

CodePudding user response:

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.

CodePudding user response:

We could use filter to filter out the required keys from the original dictionary. In this case, keys which have 0 at the 0th index.

def filter_function(item):
    key, value = item
    return key[0] == 0

def max_key(item):
    key, value = item
    return value

print(max(filter(filter_function, dictionary.items()), key=max_key))

The filter_function could be replaced with whatever condition you'd like to have.

  • Related