---
title: "Dictionaries"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 26
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 26 — Dictionaries

Lina has two hundred contacts in her phone. She types “Grandma”, and the number appears at once. The phone does not read the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) from the top, checking each name in turn: it *looks the name up*. Python has a kind of [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) made for looking things up by name.

**You already know.**

A [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) keeps [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) in order and is reached by [index](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), from 0 ([Chapter 20](https://one-course.com/books/computer-science/1/en/chapter/20-lists#ch-g7-lists)); finding an [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) in it means walking through it. A [string](https://one-course.com/books/computer-science/1/en/chapter/21-strings#def-g7-strings-string) can be cut into words with `split` ([Chapter 21](https://one-course.com/books/computer-science/1/en/chapter/21-strings#ch-g7-strings)).

## 26.1 Looking a value up by its key

**Definition 26.1 (Dictionary, key, entry).**

A *dictionary* is a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) that holds pairs: each pair, an *entry*, links a *key* to a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value). The keys are all different; `d[key]` gives the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) linked to `key`. A dictionary is written between braces, with a colon between each key and its [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value): `{"Sami": 12, "Noor": 13}`.

```python
phone = {"Grandma": "0612 345 678", "Sami": "0698 765 432", "Noor": "0655 501 020"}
print(phone["Grandma"])
print(len(phone), "contacts")
print("Leo" in phone, "Sami" in phone)
```

***Listing 26.1.** A phone book as a [dictionary](#def-g8-dictionaries-dictionary). code/grade-8/02-dictionaries/listings/contacts.py*

```
$ python contacts.py
0612 345 678
3 contacts
False True
```

***Output 26.1.** A [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) found by its [key](#def-g8-dictionaries-dictionary); `in` tests whether a [key](#def-g8-dictionaries-dictionary) is there.*

![A dictionary as two columns: each key leads to its value.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-dictionaries/fig-1cb8fff0bb4c.svg)

*A [dictionary](#def-g8-dictionaries-dictionary) as two columns: each [key](#def-g8-dictionaries-dictionary) leads to its [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value).*

Asking for a [key](#def-g8-dictionaries-dictionary) that is not there is a [runtime error](https://one-course.com/books/computer-science/1/en/chapter/23-finding-and-fixing-bugs#def-g7-finding-and-fixing-bugs-kinds), a `KeyError`:

```python
phone = {"Grandma": "0612 345 678", "Sami": "0698 765 432"}
print(phone["Leo"])
```

***Listing 26.2.** A name that is not in the [dictionary](#def-g8-dictionaries-dictionary). code/grade-8/02-dictionaries/listings/key_error.py*

```
$ python key_error.py
Traceback (most recent call last):
  File "~/session/key_error.py", line 2, in <module>
    print(phone["Leo"])
          ~~~~~^^^^^^^
KeyError: 'Leo'
[exit status 1]
```

***Output 26.2.** The last line names the missing [key](#def-g8-dictionaries-dictionary).*

Either test first with `in`, or use `get`, which returns a default [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) instead of stopping:

```python
phone = {"Grandma": "0612 345 678", "Sami": "0698 765 432"}
for name in ["Sami", "Leo"]:
    print(name, phone.get(name, "not in the contacts"))
```

***Listing 26.3.** `get` with a default. code/grade-8/02-dictionaries/listings/get_default.py*

```
$ python get_default.py
Sami 0698 765 432
Leo not in the contacts
```

***Output 26.3.** No error for Leo.*

![Finding Grandma: a walk through a list against one step in a dictionary. How a dictionary goes straight to its key is explained in the university books.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-dictionaries/fig-ecee79c1975c.svg)

*Finding Grandma: a walk through a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) against one step in a [dictionary](#def-g8-dictionaries-dictionary). How a [dictionary](#def-g8-dictionaries-dictionary) goes straight to its [key](#def-g8-dictionaries-dictionary) is explained in the university books.*

## 26.2 Creating, changing, walking through

An [assignment](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-assignment) to `d[key]` adds an [entry](#def-g8-dictionaries-dictionary) if the [key](#def-g8-dictionaries-dictionary) is new, and changes its [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) if the [key](#def-g8-dictionaries-dictionary) is already there; `del d[key]` removes an [entry](#def-g8-dictionaries-dictionary). A `for` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) over a [dictionary](#def-g8-dictionaries-dictionary) walks through its [keys](#def-g8-dictionaries-dictionary), in the order in which they were added. `d.items()` gives the [key](#def-g8-dictionaries-dictionary) and the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) together: the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) then has two [variables](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), separated by a comma.

```python
stock = {"apples": 12, "pears": 5}
stock["plums"] = 20            # a new key: a new entry
stock["apples"] = 9            # a key already there: its value changes
del stock["pears"]
print(stock)
for fruit in stock:
    print(fruit, stock[fruit])
for fruit, count in stock.items():
    print(fruit, "->", count)
```

***Listing 26.4.** Adding, changing, removing, walking. code/grade-8/02-dictionaries/listings/change_walk.py*

```
$ python change_walk.py
{'apples': 9, 'plums': 20}
apples 9
plums 20
apples -> 9
plums -> 20
```

***Output 26.4.** Three walks over the same two entries.*

Python keeps a [dictionary](#def-g8-dictionaries-dictionary) in the order of its [keys](#def-g8-dictionaries-dictionary)’ arrival; changing a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) does not move its [key](#def-g8-dictionaries-dictionary), which is why `apples` is still first.

## 26.3 Counting with a dictionary

A [dictionary](#def-g8-dictionaries-dictionary) of counts answers “how many of each?”. For each [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), its count is its old count plus one, and `get(item, 0)` gives 0 for an [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) not seen before:

`counts[word] = counts.get(word, 0) + 1`

```python
text = "the fox and the hen"
counts = {}
for ch in text:
    if ch != " ":
        counts[ch] = counts.get(ch, 0) + 1
print(counts)
print("e appears", counts["e"], "times")
```

***Listing 26.5.** Counting letters. code/grade-8/02-dictionaries/listings/count_letters.py*

```
$ python count_letters.py
{'t': 2, 'h': 3, 'e': 3, 'f': 1, 'o': 1, 'x': 1, 'a': 1, 'n': 2, 'd': 1}
e appears 3 times
```

***Output 26.5.** Each letter once, with its count.*

The same pattern counts words. This version prints the [dictionary](#def-g8-dictionaries-dictionary) after each word, to show it grow:

```python
sentence = "the fox saw the hen and the hen saw the fox"
counts = {}
for word in sentence.split():
    counts[word] = counts.get(word, 0) + 1
    print(word, counts)
```

***Listing 26.6.** Counting words. code/grade-8/02-dictionaries/listings/count_words.py*

```
$ python count_words.py
the {'the': 1}
fox {'the': 1, 'fox': 1}
saw {'the': 1, 'fox': 1, 'saw': 1}
the {'the': 2, 'fox': 1, 'saw': 1}
hen {'the': 2, 'fox': 1, 'saw': 1, 'hen': 1}
and {'the': 2, 'fox': 1, 'saw': 1, 'hen': 1, 'and': 1}
the {'the': 3, 'fox': 1, 'saw': 1, 'hen': 1, 'and': 1}
hen {'the': 3, 'fox': 1, 'saw': 1, 'hen': 2, 'and': 1}
saw {'the': 3, 'fox': 1, 'saw': 2, 'hen': 2, 'and': 1}
the {'the': 4, 'fox': 1, 'saw': 2, 'hen': 2, 'and': 1}
fox {'the': 4, 'fox': 2, 'saw': 2, 'hen': 2, 'and': 1}
```

***Output 26.6.** A new [key](#def-g8-dictionaries-dictionary) for a new word, a larger count for a word seen before.*

![The counts after each of the first six words. Only the second the changes a count instead of adding a key.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-dictionaries/fig-1c378d9b1f74.svg)

*The counts after each of the first six words. Only the second `the` changes a count instead of adding a [key](#def-g8-dictionaries-dictionary).*

## 26.4 A record as a dictionary, a table as a list of records

**Definition 26.2 (Record and field).**

A *record* is a group of [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) that describe one thing, each under a name: a *field*. In Python, a record can be a [dictionary](#def-g8-dictionaries-dictionary) whose [keys](#def-g8-dictionaries-dictionary) are the field names.

A book of a school library has a title, an author and a year: three [fields](#def-g8-dictionaries-record). A [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of such [records](#def-g8-dictionaries-record) is a table, one [record](#def-g8-dictionaries-record) per row.

```python
books = [
    {"title": "The Lighthouse Cat", "author": "Mara Quill", "year": 1998},
    {"title": "Seven Bridges", "author": "Tom Alder", "year": 2011},
    {"title": "Rain on Hilltop", "author": "June Okafor", "year": 2004},
]
for book in books:
    print(book["year"], book["title"], "by", book["author"])

recent = 0
for book in books:
    if book["year"] > 2000:
        recent = recent + 1
print(recent, "of", len(books), "books are from after 2000")
```

***Listing 26.7.** A small library: a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of three [records](#def-g8-dictionaries-record). code/grade-8/02-dictionaries/listings/books.py*

```
$ python books.py
1998 The Lighthouse Cat by Mara Quill
2011 Seven Bridges by Tom Alder
2004 Rain on Hilltop by June Okafor
2 of 3 books are from after 2000
```

***Output 26.7.** The [fields](#def-g8-dictionaries-record) of each [record](#def-g8-dictionaries-record), then a count.*

![The list of as a table: the field names head the columns, each record is a row.](https://one-course.com/images/onecourse/chapters/computer-science-1/g8-dictionaries/fig-fc7d9cae5eab.svg)

*The [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of [Listing 26.7](#lst-g8-dictionaries-books) as a table: the [field](#def-g8-dictionaries-record) names head the columns, each [record](#def-g8-dictionaries-record) is a row.*

## 26.5 Exercises

**Exercise 26.1 ★.**

With `d = {"a": 1, "b": 2, "c": 3}`, what is `d["b"]`? What does `d["d"]` do?

**Solution of Exercise 26.1.**

`d["b"]` is 2. `d["d"]` stops the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) with a `KeyError`: there is no [key](#def-g8-dictionaries-dictionary) `"d"`.

**Exercise 26.2 ★.**

`d` is the empty [dictionary](#def-g8-dictionaries-dictionary) `{}`. After `d["x"] = 1` and then `d["x"] = 5`, what are `len(d)` and `d["x"]`?

**Solution of Exercise 26.2.**

The second [assignment](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-assignment) changes the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of the [key](#def-g8-dictionaries-dictionary) `"x"`, which is already there: `len(d)` is 1 and `d["x"]` is 5.

**Exercise 26.3 ★.**

What does this [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) print?

```python
ages = {"Sami": 12, "Noor": 13, "Leo": 12}
for name, age in ages.items():
    if age == 12:
        print(name)
```

***Listing 26.8.** A walk over `items()`. code/grade-8/02-dictionaries/exercises/walk_items.py*

**Solution of Exercise 26.3.**

`Sami`, then `Leo`: the two names whose age is 12, in the order of the [dictionary](#def-g8-dictionaries-dictionary).

**Exercise 26.4 ★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `capital(country)` that looks a country up in a [dictionary](#def-g8-dictionaries-dictionary) of four capitals and returns `"not known"` for any other country.

**Solution of Exercise 26.4.**

```python
capitals = {"France": "Paris", "Italy": "Rome", "Japan": "Tokyo", "Kenya": "Nairobi"}


def capital(country):
    return capitals.get(country, "not known")


print(capital("Japan"), "/", capital("Peru"))
```

*A lookup with a default. code/grade-8/02-dictionaries/exercises/capitals.py*

It prints `Tokyo / not known`.

**Exercise 26.5 ★★.**

This [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) stops with `KeyError: 'mouse'`. Fix it so that a word missing from the [dictionary](#def-g8-dictionaries-dictionary) is kept as it is.

```python
french = {"the": "le", "cat": "chat", "eats": "mange", "fish": "poisson"}
sentence = "the cat eats the mouse"
words = []
for word in sentence.split():
    words.append(french[word])
print(" ".join(words))
```

***Listing 26.9.** A word for word translation. code/grade-8/02-dictionaries/exercises/translate_bug.py*

**Solution of Exercise 26.5.**

`french[word]` needs every word to be a [key](#def-g8-dictionaries-dictionary). With `french.get(word, word)`, a missing word gives itself back:

```python
for word in sentence.split():
    words.append(french.get(word, word))      # unknown words stay as they are
print(" ".join(words))
```

*The [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop), fixed. code/grade-8/02-dictionaries/exercises/translate_fixed.py*

It prints `le chat mange le mouse`.

**Exercise 26.6 ★★.**

This [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) should count the words of `"a rose is a rose"`. It prints `{'a': 1, 'rose': 1, 'is': 1}`. Why? Fix it.

```python
counts = {}
for word in "a rose is a rose".split():
    counts[word] = 1
print(counts)
```

***Listing 26.10.** Counts that never grow. code/grade-8/02-dictionaries/exercises/counts_bug.py*

**Solution of Exercise 26.6.**

`counts[word] = 1` sets the count to 1 each time, so a word seen twice still counts 1. The counting pattern adds one to the old count: `counts[word] = counts.get(word, 0) + 1`, which gives 2 for `a` and for `rose`.

**Exercise 26.7 ★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `most_frequent(sentence)` that returns the word that appears most often.

**Solution of Exercise 26.7.**

Count the words, then keep the best so far:

```python
def most_frequent(sentence):
    counts = {}
    for word in sentence.split():
        counts[word] = counts.get(word, 0) + 1
    best = ""
    for word in counts:
        if best == "" or counts[word] > counts[best]:
            best = word
    return best


print(most_frequent("the fox saw the hen and the hen saw the fox"))
```

*The most frequent word. code/grade-8/02-dictionaries/exercises/most_frequent.py*

It prints `the`, which appears four times.

**Exercise 26.8 ★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `invert(d)` that swaps the [keys](#def-g8-dictionaries-dictionary) and the [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of a [dictionary](#def-g8-dictionaries-dictionary) whose [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) are all different. Why must they be different?

**Solution of Exercise 26.8.**

```python
def invert(d):
    """Swap keys and values; the values must all be different."""
    result = {}
    for key, value in d.items():
        result[value] = key
    return result


print(invert({"one": 1, "two": 2, "three": 3}))
```

*[Values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) become [keys](#def-g8-dictionaries-dictionary). code/grade-8/02-dictionaries/exercises/invert.py*

The [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) become [keys](#def-g8-dictionaries-dictionary), and [keys](#def-g8-dictionaries-dictionary) are all different: if two [keys](#def-g8-dictionaries-dictionary) had the same [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), the second [entry](#def-g8-dictionaries-dictionary) would replace the first in the result.

**Exercise 26.9 ★★.**

Without running it, how many entries does a word-count [dictionary](#def-g8-dictionaries-dictionary) have for `"a rose is a rose is a rose"`? What are the counts?

**Solution of Exercise 26.9.**

Three entries: `a` 3, `rose` 3 and `is` 2.

**Exercise 26.10 ★★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `oldest(books)` that returns the [record](#def-g8-dictionaries-record) of the oldest book of a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) like the one of [Listing 26.7](#lst-g8-dictionaries-books).

**Solution of Exercise 26.10.**

```python
def oldest(books):
    best = books[0]
    for book in books:
        if book["year"] < best["year"]:
            best = book
    return best


print(oldest(books)["title"])
```

*The oldest book. code/grade-8/02-dictionaries/exercises/oldest.py*

It prints `The Lighthouse Cat` (1998).

**Exercise 26.11 ★★★.**

Votes for $c$ candidates are written on $b$ ballots. One method counts each candidate’s votes by walking all the ballots; the other walks the ballots once with a [dictionary](#def-g8-dictionaries-dictionary) of counts. How many names does each method look at? Which is better for 1 000 ballots and 50 candidates, and by how much?

**Solution of Exercise 26.11.**

The first method walks the $b$ ballots once per candidate: $c \times b$ names. The second walks them once: $b$ names. For 1 000 ballots and 50 candidates, 50 000 against 1 000: the [dictionary](#def-g8-dictionaries-dictionary) looks at 50 times fewer names, as many times fewer as there are candidates.

**Exercise 26.12 ★★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `group_by_first_letter(words)` that returns a [dictionary](#def-g8-dictionaries-dictionary) whose [keys](#def-g8-dictionaries-dictionary) are first letters and whose [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) are [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of the words that start with each.

**Solution of Exercise 26.12.**

A word whose first letter is new starts an empty [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) first:

```python
def group_by_first_letter(words):
    groups = {}
    for word in words:
        first = word[0]
        if first not in groups:
            groups[first] = []
        groups[first].append(word)
    return groups


print(group_by_first_letter(["apple", "bean", "avocado", "cherry", "banana"]))
```

*A [dictionary](#def-g8-dictionaries-dictionary) of [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list). code/grade-8/02-dictionaries/exercises/group.py*

It prints `{'a': ['apple', 'avocado'], 'b': ['bean', 'banana'], 'c': ['cherry']}`.

## 26.6 Problem: Counting the Votes

**Problem 26.1.**

Weekend problem — two ways to count an election

A class of 40 pupils elects its delegate among six candidates. Each pupil writes one name on a ballot, and the ballots are kept in a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list).

```python
"""The ballots of the weekend problem: 40 for 6 candidates, then 400 for 20."""

CANDIDATES = ["Ada", "Ben", "Chloe", "Dev", "Eva", "Femi"]
BALLOTS = [
    "Chloe", "Ada", "Eva", "Chloe", "Ben", "Dev", "Chloe", "Ada", "Femi", "Eva",
    "Chloe", "Dev", "Ada", "Chloe", "Eva", "Ben", "Ada", "Chloe", "Dev", "Eva",
    "Femi", "Chloe", "Ada", "Eva", "Chloe", "Ben", "Dev", "Ada", "Chloe", "Eva",
    "Ada", "Femi", "Chloe", "Eva", "Dev", "Ada", "Chloe", "Ben", "Eva", "Ada",
]


def many_ballots(count, candidates):
    """A longer, made-up election: ballot i goes to the candidate a fixed rule picks."""
    ballots = []
    for i in range(count):
        ballots.append(candidates[(i * i + 3 * i) % len(candidates)])
    return ballots
```

***Listing 26.11.** The ballots of the class, and a rule to make up a larger election. code/grade-8/02-dictionaries/listings/ballots.py*

**Part I — By hand.**

1. Tally the first 12 ballots by hand. Who leads?
2. How did you keep the counts? What would you do with a name not yet on your tally?

**Part II — Two programs.** The first [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) counts each candidate’s votes with a walk through all the ballots. A [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) may return two [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) separated by a comma; the caller receives them the same way, `results, looked_at = ...`.

```python
from ballots import BALLOTS, CANDIDATES


def count_per_candidate(ballots, candidates):
    """For each candidate, walk all the ballots. Also count the names looked at."""
    results = []
    looked_at = 0
    for name in candidates:
        votes = 0
        for ballot in ballots:
            looked_at = looked_at + 1
            if ballot == name:
                votes = votes + 1
        results.append(votes)
    return results, looked_at


if __name__ == "__main__":
    results, looked_at = count_per_candidate(BALLOTS, CANDIDATES)
    for i in range(len(CANDIDATES)):
        print(CANDIDATES[i], results[i])
    print("names looked at:", looked_at)
```

***Listing 26.12.** One walk per candidate. code/grade-8/02-dictionaries/listings/votes_list.py*

3. What does `looked_at` count? How often does the inner [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) run?
4. Run it. Who wins, and how many names were looked at?

The second [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) walks the ballots once:

```python
from ballots import BALLOTS


def count_once(ballots):
    """Walk the ballots once, with a dictionary of counts."""
    counts = {}
    looked_at = 0
    for ballot in ballots:
        looked_at = looked_at + 1
        counts[ballot] = counts.get(ballot, 0) + 1
    return counts, looked_at


def winner_and_margin(counts):
    best = ""
    for name in counts:
        if best == "" or counts[name] > counts[best]:
            best = name
    second = 0
    for name in counts:
        if name != best and counts[name] > second:
            second = counts[name]
    return best, counts[best] - second


if __name__ == "__main__":
    counts, looked_at = count_once(BALLOTS)
    print(counts)
    winner, margin = winner_and_margin(counts)
    print("winner:", winner, "by", margin, "votes")
    print("names looked at:", looked_at)
```

***Listing 26.13.** One walk, with a [dictionary](#def-g8-dictionaries-dictionary). code/grade-8/02-dictionaries/listings/votes_dict.py*

5. Which line is the counting pattern of this chapter?
6. How does `winner_and_margin` find the second best?
7. Run it. Do both [programs](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) agree? How many names were looked at now?
8. Why does the [dictionary](#def-g8-dictionaries-dictionary) [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) the candidates in a different order from `CANDIDATES` ?

**Part III — A larger election.** A third [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) runs both methods on the class, then on a made-up election of 400 ballots for 20 candidates:

```python
from ballots import BALLOTS, CANDIDATES, many_ballots
from votes_dict import count_once
from votes_list import count_per_candidate


def compare(ballots, candidates):
    results, by_list = count_per_candidate(ballots, candidates)
    counts, by_dict = count_once(ballots)
    print(len(ballots), "ballots,", len(candidates), "candidates:", by_list,
          "names looked at with lists,", by_dict, "with a dictionary")


names = []
for i in range(20):
    names.append("C" + str(i + 1))
compare(BALLOTS, CANDIDATES)
compare(many_ballots(400, names), names)
```

***Listing 26.14.** Both methods on two elections. code/grade-8/02-dictionaries/listings/votes_compare.py*

9. Predict the four numbers before running it.
10. Run it. Write a rule for each method in terms of the number of ballots $b$ and of candidates $c$ .
11. A country votes with 40 million ballots for 12 [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) . How many names would each method look at?
12. State the result.

**Solution of Problem 26.1.**

**1.** Chloe 4, Ada 2, Eva 2, Dev 2, Ben 1, Femi 1: Chloe leads.

**2.** One tally line per name, added the first time the name appears: exactly what a [dictionary](#def-g8-dictionaries-dictionary) of counts does.

**3.** Every name looked at; the inner [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) runs once per ballot, for each of the six candidates.

**4.** Chloe wins:

```
$ python votes_list.py
Ada 9
Ben 4
Chloe 11
Dev 5
Eva 8
Femi 3
names looked at: 240
```

***Output 26.8.** Six walks of 40 ballots.*

**5.** `counts[ballot] = counts.get(ballot, 0) + 1`.

**6.** It walks the counts again and keeps the largest count of any name other than the winner; the margin is the difference.

**7.** They agree, with 40 names looked at instead of 240:

```
$ python votes_dict.py
{'Chloe': 11, 'Ada': 9, 'Eva': 8, 'Ben': 4, 'Dev': 5, 'Femi': 3}
winner: Chloe by 2 votes
names looked at: 40
```

***Output 26.9.** One walk of 40 ballots.*

**8.** A [key](#def-g8-dictionaries-dictionary) enters the [dictionary](#def-g8-dictionaries-dictionary) when its name first appears on a ballot: Chloe is on the first ballot, Ada on the second.

**9.** $6 \times 40 = 240$ and 40; $20 \times 400 = 8\,000$ and 400.

**10.**

```
$ python votes_compare.py
40 ballots, 6 candidates: 240 names looked at with lists, 40 with a dictionary
400 ballots, 20 candidates: 8000 names looked at with lists, 400 with a dictionary
```

***Output 26.10.** The two methods on two elections.*

The [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) method looks at $c \times b$ names, the [dictionary](#def-g8-dictionaries-dictionary) at $b$.

**11.** 480 million names with [lists](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), 40 million with a [dictionary](#def-g8-dictionaries-dictionary).

**12.** **Result.** Counting with one walk per candidate looks at candidates $\times$ ballots names (240 for the class, 8 000 for the larger election); counting with a [dictionary](#def-g8-dictionaries-dictionary) looks at each ballot once (40, then 400).
