0

I have a for loop which ends with dictionary:

print("A: {0}, B: {2}, C: {1}".format(k,score,n_clusters))

A: -11.88, B: 8, C: 0.0548
A: -10.79, B: 76, C: 0.0049
A: -6.167, B: 57, C: -0.0018
A: -2.569, B: 94, C: -0.0062
A: -1.667, B: 2, C: 0.3269 # same value
A: -1.356, B: 2, C: 0.3269 # same value

I want to save value of B based on maximum values of C which is 0.3269once even this value is repeated several times.

Desired output:

final_score = 2
Massifox
  • 4,369
  • 11
  • 31
Mamed
  • 1,102
  • 8
  • 23
  • Are the inputs lists...? – yatu Sep 13 '19 at 10:33
  • Possible duplicate of [Getting key with maximum value in dictionary?](https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary) – PV8 Sep 13 '19 at 10:34
  • if you think about this in 2minutes: https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary you will be able to solve it... – PV8 Sep 13 '19 at 10:35

1 Answers1

2

If I understand your question correctly, given the following:

lst = [{'A': -11.88, 'B': 8, 'C': 0.0548},
    {'A': -10.79, 'B': 76, 'C': 0.0049},
    {'A': -6.167, 'B': 57, 'C': -0.0018},
    {'A': -2.569, 'B': 94, 'C': -0.0062},
    {'A': -1.667, 'B': 2, 'C': 0.3269},
    {'A': -1.356, 'B': 2, 'C': 0.3269}]

This code is for you:

final_score = max(lst, key=lambda x:x['C'])['B']

If you don't have the dictionary values ​​saved in a list, but want to find the maximum within your loop, just do:

final_score = None
max_clusters = float("-inf")
for i in foo_range: # your loop 
    # do something and retrieve 'score' and 'n_clusters' 
    if max_clusters < n_clusters:
        final_score = score
        max_clusters = n_clusters

print(final_score)
Massifox
  • 4,369
  • 11
  • 31
  • What if I do not have "lst". I mean I did not store values somewhere. It gives me output with `print()` – Mamed Sep 13 '19 at 12:12
  • Then it is simply a matter of calculating the maximum within your loop. I updated my answer taking into account your last request. – Massifox Sep 13 '19 at 12:51