[英]How do i find the largest value of an item in a nested dict in python?
我有以下帶有嵌套字典“Emotions”的字典:
我試圖找到一種簡單的方法來返回具有最大 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"
}
],
}
]
我試過dictmax = max(dict[Emotions][Confidence] key=dict.get)
但這似乎不起作用,我不知所措。 我覺得應該有一種簡單的方法來檢索類型,基於 Confidence 的值。
你可以試試這個。
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'])
Ch3steR 的答案有效,但我想提出一個帶有pandas
的解決方案,它是一個用於處理數據分析的庫(使用 DataFrame 對象,可以輕松進行數據操作)。
在您的示例中,讓我們僅獲取示例的相關部分:
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'}]
這可以轉換為一個 pandas DataFrame 對象:
import pandas as pd
pd.DataFrame(emotions)
產量
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
此對象可以按任何列(例如 Confidence)排序,使用.sort_values
方法,可以使用.tail(2)
方法選擇最后兩行(或任何其他數量)的行,最后是 'Type' 列可以選擇。 總結一下:
pd.DataFrame(emotions).sort_values('Confidence').tail(2)['Type'].values
產量
array(['ANGRY', 'CONFUSED'], dtype=object)
如果你想要前 1,而不是前 n(對於 n>1),搜索最大值而不是排序更快更簡單:
emotions.loc[emotions['Confidence'].idxmax(),'Type']
產量
'CONFUSED'
這並不比 Ch3steR 的答案快,但代碼更直接(一旦您了解了 pandas 庫),並且易於“擴展”到您以后可能需要的更復雜的數據分析。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.