0

I have a result from an API call that comes in and looks like this:

dict1 = {"label": 'LABEL_0', 'score': 0.85}
dict2 = {"label": 'LABEL_1', 'score': 0.10}
dict3 = {"label": 'LABEL_2', 'score': 0.10}
list([dict1, dict2, dict3])

[{'label': 'LABEL_0', 'score': 0.85},
 {'label': 'LABEL_1', 'score': 0.1},
 {'label': 'LABEL_2', 'score': 0.1}]

How would I get the label with the max label and the score associated as two variables?

So for this example I would want e.g. want

label_val = "LABEL_0"

score_val = 0.85

I cant figure out a way of doing this. I tried un-listing using the * but that did not help

user3234242
  • 165
  • 7
  • 2
    `max(list_of_dict, key=lambda x: x['score'])`? – Axe319 Dec 07 '22 at 17:00
  • This isn't a `numpy` task. You have a list. And `numpy` doesn't do anything special with `dict`. – hpaulj Dec 07 '22 at 17:06
  • Does this answer your question? [How to find the min/max value of a common key in a list of dicts?](https://stackoverflow.com/questions/5320871/how-to-find-the-min-max-value-of-a-common-key-in-a-list-of-dicts) – Pranav Hosangadi Dec 07 '22 at 17:19
  • You can at least search for the [title of your question](https://www.google.com/search?q=How+to+get+the+maximum+value+from+a+list+of+dictionarys+python) as part of the [research you're supposed to do before asking](//meta.stackoverflow.com/a/261593/843953) – Pranav Hosangadi Dec 07 '22 at 17:20

1 Answers1

1

To get the maximum value of score along label i have:

  1. Created an empty list and appended the score values to get max score value in it (as max function would work on a list).

  2. Compare the max value with the scores present in dictionaries (within the list).

  3. At last print the keys & values of that dictionary(having max score value).

dict1 = {"label": 'LABEL_0', 'score': 0.85}
dict2 = {"label": 'LABEL_1', 'score': 0.10}
dict3 = {"label": 'LABEL_2', 'score': 0.10}
d=list([dict1, dict2, dict3])

b=[]    
for i in d:
    for x,y in i.items():
      if x=="score":          
          b.append(y)
c=max(b)
for i in d:
    for x,y in i.items():
        if y==c:
          for m,n in i.items():
              print(m,n)

This returns:

label LABEL_0
score 0.85