Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 {(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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading