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

Find max value in json even when not existing in some strings Python

I have a json like this:

{
'tester': [{
    'bbox': [159.50451898338267, 184.94235347135182, 342.8551702886517, 443.9425698127003],
    'score': 0.9999966621398926,
    'post': 43.10764727758942,
    'class': 'Test'
}, {
    'bbox': [564.0261332136855, 14.13539395667492, 580.3409768964439, 38.84439850201004],
    'score': 0.9937067627906799
}, {
    'bbox': [462.02023603048644, 10.929288388749383, 477.8772119836293, 29.733179334594],
    'score': 0.9837657809257507
}],
'status': 'ok'

}

The json can contain more strings.

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

Im trying to get the max value from Post using this code:

max_age = max(quality['tester'], key=lambda x: x['post'])

The problem im facing is that the key Post does not exists in every string so I get a key error using this code

>Solution :

Assuming you want to ignore entries that do not contain the post key, this should work:

max_age = max(filter(lambda x: 'post' in x, quality['tester']), key=lambda x: x['post'])

You may also want to provide a default value (otherwise max will crash if there is the sequence is empty), or even this variant if you are only interested in the maximum post value, and not the entry whose post value is maximal:

max_age = max(x['post'] for x in quality['tester'] if 'post' in x))
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