Obtaining a key with the maximum value in a dictionary in python

Viewed 2602

I had a question to printout the word with the maximum frequency in a .txt file and used the max function to obtain the key with maximum value as follows:

freq=dict()
f=open('words.txt','r')
for line in f:
     words=line.split()
     for word in words:
     word=word.lower()
     freq[word]=freq.get(word,0)+1

maximum=max(freq)
print(maximum)

But after cross-checking I found out that a wrong key was provided as output. the second part of the code was changed as follows:

maximum = max(freq, key=freq.get)
print(maximum)

Here, the output obtained matched with the word that occurred maximum times.

I would like to know the reason for the different results obtained in two cases and which way is better if dealing with similar situations/problems in future. Thank You.

4 Answers

It happens because max does not know how to compare the elements of your dict. So if you don't provide a key, it compares them alphabetically by default. But when you give it a function, it will use that function and find max according to that function:

>>> counts = {"a": 10, "b": 5, "c": 20, "d": 15}
>>> max(counts)
'd'
>>> max(counts, key=counts.get)
'c'

max(freq) returns the maximum key in the dictionary, i.e. the last one alphabetically if the keys are strings

When you add the key=freq.get keyword argument, you get the element x with the maximum value of freq.get(x)

This is because max(freq) is comparing all words vs each other.

Whereas using key=freq.get you are comparing the values in the dict and returning the key with the highest value.

It can arrive that you have more than one key with a maximum value. The option

maximum = max(freq, key=freq.get)

will return the key associated with the first value. If you want to have another one you can use the following code:

def select_key_with_max_value(my_dict):
    my_lst=[(a,b) for (a,b)in my_dict.items()]    
    max_value = max(my_lst)[1]
    lst_max_values = [(key,values) for (key,values) in my_dict.items()\
                     if values ==max(my_lst)[1] ]
    lst_max_values =sorted(lst_max_values)
    num = len(lst_max_values)
    print ("There are {} items with a maximum value.".format(num))
    order = int(input("Which of the key(s) do you want by the keys' alphabetic 
                       order?"))-1
    return lst_max_values[order][0]

As an exemple:

Tv = { 'GameOfThrones':100, 'BreakingBad':100,'TMKUC' : 100} 

select_key_with_max_value(Tv)

results in:

There are 3 items with a maximum value.
Which of the key(s) do you want by the keys' alphabetic order?3
'TMKUC'
Related