Reputation: 37
I made a quick bit of code that checks a list of input words by the user and counts how many of the same word the user has typed. if print is input it is supposed to print the most frequent word used as well as how many times it was used for example The word 'Hello' has been used '12' times i am just not sure how to get it to iterate through the dictionary and find the most frequent word
Here is the code
d = {}
L2 = []
Counter = 0
checker = -1
while True:
Text = str(input('enter word '))
Text = Text.lower()
if Text in ['q', 'Q']:
break
if Text in ['Print', 'print']:
for word in L2:
if word not in d:
counter = L2.count(word)
d[word] = counter
#This part does not work
for value in d[0]:
if checker < value:
checker = value
print(checker)
#This part does
L2.append(Text)
Upvotes: 0
Views: 138
Reputation: 4213
d = {}
L2 = []
while True:
text_input = input('enter word ') # input by default stores values in string format
text_input = text_input.lower()
if text_input == 'q': # you have used text_input.lower() so you don't need to use it is 'q' or 'Q' it will never be 'Q'
break
elif text_input == 'print':
for item in set(L2): # set(L2) will only keep unique values from list L2
d[item] = L2.count(item) # counts for all unique items and append it to dictionary
for word, count in d.items(): # by using this loop you can print all possible max values i.e. if two word has same max occurance it will print both
if count == max(d.values()):
print("Word : {} repeated {} times.".format(word, count))
else:
L2.append(text_input) # input is neither 'q' nor 'print' hence append word in list
Upvotes: 1