name=input('Enter a file:') handle=open(name) counts=dict() for line in handle: words=line.split() for word in words: counts[word]=counts.get(word,0)+1 bigcount=None bigword=None for word,count in counts.items(): if bigcount is None or count>bigcount: bigcount=count bigword=word print(bigword, bigcount)
Line 7 at the top just looks for the key (word) in the dict (counts) and if not there sets up the default return value of 0
Then it adds 1 to the result of the get and stores it in counts again
So essentially it creates a new key-value pair of the word does not exist and adds 1 to the key-value pair of the word does exist (in the end the dict has a list of words and the number of times they occurred from 1 up)
Then later the for loop loops through the list of words and their counts
And prints out the first word and it’s count followed by every word and it’s count provided that the next word’s count is larger than the previous one printed.
Thanks a lot for detailed explanation
Do you have a sample of what the file looks like?