Home > Back-end >  How to get the maximum value from a list of dictionarys
How to get the maximum value from a list of dictionarys

Time:12-08

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

CodePudding user response:

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
  • Related