top of page
Prostate Gland releases PSA molecules (15).png

DICTIONARIES

Problem:

Given:  A string s of length at most 10000 letters.

​

Return: The number of occurrences of each word in s, where words are separated by spaces. Words are case-sensitive, and the lines in the output can be in any order.

​

Sample Dataset: We tried list and we tried dicts also we tried Zen

​

Sample Output:  

​

and 1

We 1

tried 3

dicts 1

list 1

we 2

also 1

Zen 1

Solution:

To solve this problem, nifty dictionaries come to the rescue. First we break up the text using the split() method and store the words in a list variable called words. 

< >

text = "We tried list and we tried dicts also we tried Zen"

words = text.split()

Then a blank dictionary is created. The words are looped through, and any word not present in the dictionary will be added to it and initialized with a count of 1. If the word being looped through is present in the dictionary, 1 is simply added to its key's associated value.

​

And then the word is printed alongside its count:

< >

dict = {}

for word in words:

if word not in dict:

dict[word] = 1

else:

dict[word] += 1

 

for key, value in dict.items():

print(key, value)

Output:

and 1

We 1

tried 3

dicts 1

list 1

we 2

also 1

Zen 1

Copy and paste the output you get from running your code on the sample data onto the Rosalind answer terminal and submit. Annnd get yourself a cookie!

Subscribe to my mailing list and never miss a blogpost or new puzzle!

  • White Instagram Icon

Thanks for submitting!

bottom of page