Python 3D Academyবাংলা

Dictionaries in practice

🌍 In real life. A teacher sorts homework into piles by class: every paper from class 6 in one pile, class 7 in another. A new class gets a new, empty pile first. And a phone's contact card holds a little record inside each name: number, email, birthday.

Dictionaries can do both: hold a list per key, and hold another dictionary per key.

The idea in one sentence: a dictionary's values can be lists or dictionaries, which lets you group items under a key and look things up in one step.

Its words:

  • grouping: a list per key, filled with groups[key].append(item)
  • seen with positions: a dictionary remembering where each value was met
  • nested dictionary: a dictionary inside a dictionary, reached with two pairs of brackets

Step by step, grouping words by first letter:

  1. For "ant", the key is "a". It's new, so make groups["a"] = [], then append "ant".
  2. For "bee", make groups["b"] = [], then append.
  3. For "ape", "a" exists, so just append to it.
words = ["ant", "bee", "ape", "bat"]
groups = {}
for w in words:
    first = w[0]
    if first not in groups:
        groups[first] = []
    groups[first].append(w)
print(groups)

A dictionary also answers "have I already seen the number I need?" instantly. Here seen remembers each number's position. For every number, the partner we need is target - n. If the partner is already in seen, we've found the pair.

nums = [2, 7, 11, 15]
target = 18
seen = {}
for i, n in enumerate(nums):
    need = target - n
    if need in seen:
        print(seen[need], i)
        break
    seen[n] = i
11 needs 7, and 7 was seen at position 1: the answer is positions 1 and 2.

Dictionaries can even hold other dictionaries. Use two sets of brackets to reach inside:

people = {"Ana": {"age": 9, "city": "Dhaka"}, "Bo": {"age": 11, "city": "Sylhet"}}
print(people["Ana"]["city"])
print(people["Bo"]["age"])

What it costs: the pair-finding trick. To find two numbers that add up to a target, the obvious way tries every pair with a nested loop: about n × n checks, 100 million for 10,000 numbers. The seen dictionary needs one pass: for each number, one quick lookup for its partner, so about 10,000 steps. This trade, a little memory for a lot of speed, is one of the most useful ideas in programming; Worlds 6 and 7 use it again and again.

Mistakes and edge cases.

  • Appending to a key that has no list yet. groups["c"].append(w) gives a KeyError; create the list first.
  • One bracket too few. people["Ana"] is a whole dictionary; you need people["Ana"]["city"].
  • Adding to seen too early. In the pair finder, check for the partner before adding the current number, or a number could pair with itself.
  • The same list for every key. groups[k] = shared with one list puts everything in one pile; create a fresh [] per key.

Quiz

  1. What does this print?

    groups = {}
    for w in ["ax", "by", "aw"]:
        if w[0] not in groups:
            groups[w[0]] = []
        groups[w[0]].append(w)
    print(groups)
  2. What does this print?

    p = {"Ana": {"age": 9}}
    print(p["Ana"]["age"])
  3. What does this print?

    nums = [3, 4, 5]
    seen = {}
    for i, n in enumerate(nums):
        if 9 - n in seen:
            print(seen[9 - n], i)
        seen[n] = i
  4. In the pair-finding loop, why is each number's position stored as its value in seen?

    • So we can say where the partner number was
    • Because keys must be numbers
    • To sort the numbers
  5. Which line has a mistake?

    groups = {}
    groups["a"].append("ant")
    print(groups)

Coding tasks

  1. Ask for some words on one line. Group them by length: print a dictionary where each length leads to the list of words with that length, in the order they appeared.

  2. Ask for whole numbers on one line, then a target number. Exactly two of the numbers add up to the target. Print their two positions, smaller first, separated by a space.

  3. Ask for a note, then for the letters you have (a magazine), one per line. Each magazine letter can be used once. Print True if you can make the note, otherwise False.