donpresente donpresente - 11 months ago 118
JSON Question

Python: obtain max from json file

I have this json file

myjson=[{u'faceRectangle': {u'height': 72, u'left': 214, u'top': 125, u'width': 72}, u'scores': {u'anger': 0.180509463,
u'contempt': 1.50903434e-05, u'disgust': 0.008213697, u'fear': 0.418243885, u'happiness': 0.0259612668, u'neutral': 0.0001996803, u'sadness': 0.00102899456, u'surprise': 0.365827948}}]

I want to print from
the sentiment that has the biggest probability with its probability next to it.

Any suggestion?


Answer Source

You can use the builtin max() function with a key that selects the probability value for each item in the dictionary:

>>> myjson = [{'faceRectangle': {'left': 214, 'width': 72, 'top': 125, 'height': 72}, 'scores': {'surprise': 0.365827948, 'disgust': 0.008213697, 'sadness': 0.00102899456, 'contempt': 1.50903434e-05, 'happiness': 0.0259612668, 'anger': 0.180509463, 'neutral': 0.0001996803, 'fear': 0.418243885}}]
>>> max(myjson[0]['scores'].items(), key=lambda x: x[1])
('fear', 0.418243885)

myjson[0] selects the first dictionary from the list and max() is then applied to the nested scores dictionary.

You can also use operator.itemgetter() as the key function:

from operator import itemgetter
max(myjson[0]['scores'].items(), key=itemgetter(1))