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.