Search code examples
pythonfor-loopsplitcounter

How to print the same iteration twice?


The prompt: Write a program that reads a list of words. Then, the program outputs those words and their frequencies.

Ex: If the input is:

hey hi Mark hi mark

the output is:

hey 1



hi 2

Mark 1

hi 2

mark 1

My Code:

from collections import Counter
user.input = input().split()
count = counter(user_input)

for key, value in count.items():
    print('{} {}'.format(key, value))

I have pretty much solved the question but for some reason my output won't print out the 2nd "hi 2" as shown in the question prompt above.


Solution

  • You can iterate using the given sentence:

    from collections import Counter
    user_input = input().split()
    count = Counter(user_input)
    
    for word in user_input:
        print(f'{word} {count[word]}')
    

    Output:

    hey 1
    hi 2
    Mark 1
    hi 2
    mark 1