Counting things
Count words, votes and letters. A classic data science move.
Code runs right here in your browser. Nothing to install.
Learn it
counts[x] = counts.get(x, 0) + 1 counts anything.
Counting how often each thing appears is called a frequency count, and dictionaries are perfect for it. Each key is the thing, each value is its count.
The pattern: start with an empty dictionary, loop through the items, and for each one do counts[item] = counts.get(item, 0) + 1.
To split a sentence into words use sentence.split(). To find the most common item, use max(counts, key=counts.get).
votes = ["pizza", "tacos", "pizza", "sushi", "pizza", "tacos"] counts = {} for v in votes: counts[v] = counts.get(v, 0) + 1 print(counts) print("Winner:", max(counts, key=counts.get))
Try it yourself
+10 XPCount how many times each letter appears in the word "banana" and print the dictionary: {'b': 1, 'a': 3, 'n': 2}.
Create a free account to start this lab
Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.
Capture the flag
+10 XPWhat does "I like code".split() return?
Create a free account to start this lab
Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.
Word frequency
+20 XPCount the words in the text (make it all lowercase first). Print each word with its count in alphabetical order, like the: 3, then print Most common: the.
Create a free account to start this lab
Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.