Python Arena
Step 4 of 6

Counting and grouping

Counting how many times each thing appears is one of the most common jobs for a dictionary. The things become the keys, and their counts the values:

colors = ["red", "blue", "red", "green", "blue", "red"]

counts = {}
for color in colors:
    if color not in counts:
        counts[color] = 0
    counts[color] += 1

print(counts)
Output
{'red': 3, 'blue': 2, 'green': 1}

not in is the opposite of in: it's true when the key is not in the dictionary. The first time a color comes up, it isn't a key yet, so the loop adds it with the count 0. Then, every time, its count goes up by one.

Without the if, the very first += stops the program. += reads the old value before it adds to it, and there is no old value yet:

colors = ["red", "blue"]
counts = {}
for color in colors:
    counts[color] += 1
Python stops with
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    counts[color] += 1
    ~~~~~~^^^^^^^
KeyError: 'red'

Grouping

The same pattern can sort things into groups. The values are lists, and each thing is appended to the list of its group. Here students are grouped by their grade:

results = [["Ada", 5], ["Max", 3], ["Lin", 5], ["Kim", 4], ["Bo", 3]]

by_grade = {}
for result in results:
    name = result[0]
    grade = result[1]
    if grade not in by_grade:
        by_grade[grade] = []
    by_grade[grade].append(name)

for grade in sorted(by_grade):
    print(grade, by_grade[grade])
Output
3 ['Max', 'Bo']
4 ['Kim']
5 ['Ada', 'Lin']

The first time a grade comes up, it gets an empty list. Then the name goes into the list of its grade. Both patterns have the same shape: make sure the key exists, then update its value.

Your task

Challenge 1 of 3

Fill in the blanks so the function letter_counts(text) returns a dictionary with how many times each character appears in the string. For example, letter_counts("banana") returns {'b': 1, 'a': 3, 'n': 2}.

Challenge 2

Write a function group_by_length(words) that returns a dictionary in which the keys are word lengths and the value of each length is a list of the words of that length, in their original order.

For example, group_by_length(["sun", "moon", "sky", "star"]) returns {3: ['sun', 'sky'], 4: ['moon', 'star']}.

Challenge 3

Write a program that counts votes. It asks for votes with the prompt Vote: until the user types an empty line. Then it prints each option with its number of votes, in the order the options first got a vote. An example run:

Vote: pizza
Vote: tacos
Vote: pizza
Vote:
pizza: 2
tacos: 1