开发者社区 问答 正文

如何在python的嵌套字典中找到项目的最大值?

我有以下字典,带有嵌套的字典“情感”:

我正在尝试找到一种简单的方法来返回具有最大2个“信心”值的前2个“情感”类型(在此dict中,它是“ 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"
            }
        ],
    }
]

我已经尝试过类似dictmax = max(dict [Emotions] [Confidence] key = dict.get)的事情,但这似乎没有用,我很茫然。我觉得应该有一种简单的方法来根据Confidence的值只检索Type。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 12:36:05 603 分享 版权
1 条回答
写回答
取消 提交回答
  • 你可以试试看

    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'}] *您也可以使用nlargest。 from heapq import nlargest for d in a: out=nlargest(2,d['Emotions'],key=lambda x:x['Confidence'])

    回答来源:stackoverflow

    2020-03-24 12:36:12
    赞同 展开评论