0

I have a dictionary that looks like this.

    CV    Scores
0    2  0.966667
1    3  0.979984
2    4  0.979701
3    5  0.980000
4    6  0.979938
5    7  0.973639
6    8  0.973214
7    9  0.986420
8   10  0.973333
9   11  0.974242
10  12  0.973611
11  13  0.974359
12  14  0.974206

I want to extract the CV value for the largest Score value.

So, in this case, the largest Score value is 0.986 and I want to print the CV value of 9.

Please help.

jpp
  • 159,742
  • 34
  • 281
  • 339
BEN
  • 19
  • 5
  • The problem is that there may be multiple such keys. What do you want to do in that case? And anyway, it's going to be relatively slow, dictionaries are designed to do the opposite. – RemcoGerlich Jun 10 '18 at 13:33
  • This looks like a Pandas dataframe rather than a dictionary. Are you sure this is a `dict` ? – jpp Jun 10 '18 at 13:50
  • @eyllanesc, Don't think this is a duplicate of the question you have marked (unclear, possibly) until my question above has been answered. So voting to reopen. – jpp Jun 10 '18 at 20:17
  • 2
    @jpp I see that it is a duplicate except that the asker of new information, I can not assume things, I could assume it if the asker would mention pandas somewhere but it does not. In conclusion I think that my closing vote is valid so far – eyllanesc Jun 10 '18 at 20:20
  • @eyllanesc, You're right, you can't assume things. But you *can* vote to close as Unclear *and let the community decide*. – jpp Jun 10 '18 at 20:21
  • @jpp That is obvious and I am not indicating anything against it. :) – eyllanesc Jun 10 '18 at 20:22

2 Answers2

1

You can do it like first sort the dictionary by value and then print the key of the last element.

import operator
dictionary={2:0.966667,3:0.979984,9:0.986420, 8:0.973214,}
l=sorted(dictionary.items(),key=operator.itemgetter(1))
#it will return the list of tuples sorted by value (as 1 pass as an argument of itemgetter u can pass 0 for sort by key)
print(l[-1][0]) #print the key of last index
-1

pandas

From your input, it appears you have a Pandas dataframe. If this is the case, you can use pd.DataFrame.iloc. Note this will be more efficient than dictionary-based methods, since Pandas holds numeric data in contiguous memory blocks. Given a dataframe df:

import pandas as pd

# only one max value exists
res = df['CV'].iloc[df['Scores'].idxmax()]  # 9

# for multiple max values
res = df.loc[df['Scores'] == df['Scores'].max(), 'CV']

dict

If you really do have a dictionary, you can efficiently calculate the maximum score via heapq. Then use a generator expression with next to extract the relevant key. Given a dictionary d:

import heapq

val = heapq.nlargest(1, d.values())[0]
res = next(k for k, v in d.items() if v == val)  # 9
jpp
  • 159,742
  • 34
  • 281
  • 339