killyb :
I have the following dict with a nested dict "Emotions":
I am trying to find an easy way to return the top 2 Emotion "Type" with largest 2 "Confidence" values ( in the case of this dict, it's "CONFUSED" & "ANGRY"
[
{
"AgeRange": {
"High": 52,
"Low": 36
},
"Emotions": [
{
"Confidence": 22.537073135375977,
"Type": "ANGRY"
},
{
"Confidence": 1.3983955383300781,
"Type": "SAD"
},
{
"Confidence": 1.2260702848434448,
"Type": "DISGUSTED"
},
{
"Confidence": 2.291703939437866,
"Type": "FEAR"
},
{
"Confidence": 8.114240646362305,
"Type": "HAPPY"
},
{
"Confidence": 10.546235084533691,
"Type": "SURPRISED"
},
{
"Confidence": 18.409439086914062,
"Type": "CALM"
},
{
"Confidence": 35.47684097290039,
"Type": "CONFUSED"
}
],
}
]
i have tried things like dictmax = max(dict[Emotions][Confidence] key=dict.get)
but that doesnt seem to work, and i am at a loss. I feel like there should be an easy way to retrieve just the Type, based upon the value of Confidence.
Ch3steR :
You can try this.
for d in my_list:
out=sorted(d['Emotions'],key=lambda x:x['Confidence'],reverse=True)[:2]
[{'Confidence': 35.47684097290039, 'Type': 'CONFUSED'},
{'Confidence': 22.537073135375977, 'Type': 'ANGRY'}]
You can use nlargest
also.
from heapq import nlargest
for d in a:
out=nlargest(2,d['Emotions'],key=lambda x:x['Confidence'])