Skip to the content

Counting with dictionaries

Python · Unit 7: Dictionaries

A dictionary is great for counting: each different thing is a key and its value is how many times it showed up.

If the key is already there, add one; if not, create it with 1.

counts = {}
for letter in "banana":
    if letter in counts:
        counts[letter] += 1
    else:
        counts[letter] = 1
print(counts)

Prints

{'b': 1, 'a': 3, 'n': 2}

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Complete what happens the first time a letter shows up.

  3. 3. Complete the code

    Complete it to count how many times each fruit shows up.

  4. 4. Predict the output

    What does this code print?

  5. 5. Find the bug

    This program should count how many times each animal shows up. Which line has the bug?

  6. 6. Predict the output

    What does this code print?

  7. 7. Put the lines in order

    Put in order the function that returns how many times each character of a text shows up.

  8. 8. Multiple choice

    counts already has the words of a text counted. What does this code do?

  9. 9. Find the case that fails

    tally(text) should count each letter ignoring case: A and a are the same letter. Which call does it fail with?

  10. 10. Write the code

    Write most_repeated(words), which takes a list of words and returns the one that repeats the most. If there's a tie, the one that showed up first wins. The list is never empty.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →