简体   繁体   English

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

[英]How do i find the largest value of an item in a nested dict in python?

I have the following dict with a nested dict "Emotions":我有以下带有嵌套字典“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"我试图找到一种简单的方法来返回具有最大 2 个“置信度”值的前 2 个情感“类型”(在这个字典的情况下,它是“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.我试过dictmax = max(dict[Emotions][Confidence] key=dict.get)但这似乎不起作用,我不知所措。 I feel like there should be an easy way to retrieve just the Type, based upon the value of Confidence.我觉得应该有一种简单的方法来检索类型,基于 Confidence 的值。

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.您也可以使用nlargest

from heapq import nlargest
for d in a:
    out=nlargest(2,d['Emotions'],key=lambda x:x['Confidence'])

Ch3steR's answer works, but I'd like to propose a solution with pandas , which is a library for dealing with data analysis (using DataFrame objects, which allow for easy data manipulation). Ch3steR 的答案有效,但我想提出一个带有pandas的解决方案,它是一个用于处理数据分析的库(使用 DataFrame 对象,可以轻松进行数据操作)。

In your example, let's just take the relevant part of the example:在您的示例中,让我们仅获取示例的相关部分:

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'}]

This can be cast into a pandas DataFrame object:这可以转换为一个 pandas DataFrame 对象:

import pandas as pd
pd.DataFrame(emotions)

yields产量

    Confidence  Type
0   22.537073   ANGRY
1   1.398396    SAD
2   1.226070    DISGUSTED
3   2.291704    FEAR
4   8.114241    HAPPY
5   10.546235   SURPRISED
6   18.409439   CALM
7   35.476841   CONFUSED

This object can be sorted by any column (eg Confidence), with the .sort_values method, the last two (or any other number) of rows can be selected with the .tail(2) method, and finally, the 'Type' column can be selected.此对象可以按任何列(例如 Confidence)排序,使用.sort_values方法,可以使用.tail(2)方法选择最后两行(或任何其他数量)的行,最后是 'Type' 列可以选择。 To sup it up:总结一下:

pd.DataFrame(emotions).sort_values('Confidence').tail(2)['Type'].values

yields产量

array(['ANGRY', 'CONFUSED'], dtype=object)

If you want the top 1, and not top n (for n>1), it's faster and simpler to search for the maximum instead of sorting:如果你想要前 1,而不是前 n(对于 n>1),搜索最大值而不是排序更快更简单:

emotions.loc[emotions['Confidence'].idxmax(),'Type']

yields产量

'CONFUSED'

This is not faster than Ch3steR's answer, but the code is more straight-forward (once you know the pandas library), and easy to "scale up" to more complex data analysis which you might need later on.这并不比 Ch3steR 的答案快,但代码更直接(一旦您了解了 pandas 库),并且易于“扩展”到您以后可能需要的更复杂的数据分析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何在 Python 中的列表中找到最小值或最大值 - How do i find the smallest or largest value in a list in Python Python-如何根据嵌套字典中的值返回字典键? - Python - How do I return a dict key according to value in nested dict? 如何在用户在python中提供的2D列表中找到最小,最大值和总数以及平均值? - How do I find the smallest, largest value and total and the average in a 2D list that the user provides in python? 如何从字典值中删除列表项? - How do I remove a list item from a dict value? 在python中,如何使用动态数量的嵌套迭代嵌套的dict? - in python, how do i iterate a nested dict with a dynamic number of nests? 当Python认为值是字符串时,如何在字典中找到最大值? - How do I find the max value in a dict when Python thinks the values are strings? 如何找到第一个值是python中最大的列表 - How to find the list with the the first value is the largest in python 如何在字典中获取列表中字典项的值? - How do I get the value of a dict item within a list, within a dict? 如何在另一个字典中的Python字典中查找特定项目? - How to find specific item in a Python dict within another dict? 如何通过在 python 中的分隔符上拆分键来从 dict 创建嵌套的 dict? - How do I create a nested dict from a dict by splitting the keys on a delimiter in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM