JEPA4Japan · tutorials

Dictionaries and Sets

1,113 words 6 min read #Python

Build lookups with hashable keys, count occurrences, test membership, and remove duplicates.

Course progress Course outline 24 of 24 lessons available

Dictionaries are labeled drawers

A list answers “what is at position 0?” A dictionary answers “what is in the minutes drawer?” Each drawer has a unique key and one value.

  1. Key "topic" names a drawer
  2. Dictionary finds the matching drawer
  3. Value "Lists" is inside
A meaningful key leads to its value.
session = {
    "topic": "Lists",
    "minutes": 35,
    "completed": True,
}

print(session["topic"])
print(session["minutes"])
Lists
35

Dictionaries preserve insertion order in modern Python, but their main job is lookup by key—not numbered position and not automatic sorting.

Open, add, update, and remove drawers

Square brackets read a required key. Assignment adds a new key or replaces the value behind an existing one.

progress = {"Lists": 1, "Tuples": 1}
progress["Dictionaries"] = 1
progress["Lists"] = 2

print(progress)
print("Lists" in progress)
print("Sets" in progress)
{'Lists': 2, 'Tuples': 1, 'Dictionaries': 1}
True
False

For a dictionary, in checks keys, not values. A missing square-bracket key raises KeyError. When missing is expected, get() can provide a deliberate default:

scores = {"Lists": 0}

print(scores.get("Lists", 0))
print(scores.get("Sets", 0))
print("Lists" in scores)
print("Sets" in scores)
0
0
True
False

The first 0 is stored; the second means missing. get() alone cannot tell those meanings apart. del mapping[key] removes a known key. mapping.pop(key) removes it and returns its value. Both can fail for a missing key unless you check first or intentionally give pop() a default.

Loop over items() when you need both pieces:

for topic, count in progress.items():
    print(f"{topic}: {count}")

keys() visits keys and values() visits values.

Keys need a steady shape

A dictionary uses a hash to find the right drawer quickly. A key must be hashable: its hash must stay stable, and equal keys must agree on that hash.

  1. String "Lists"
  2. Number 42
  3. Fixed tuple (3, 5)
  4. Changing list [3, 5]
Stable, hashable values can be dictionary keys and set members.

Strings, integers, and tuples containing only hashable parts are common keys. Lists, dictionaries, and sets are mutable and unhashable, so they cannot be keys. A tuple containing a list is also unhashable. Dictionary values may be any Python object.

A counter is a perfect use for get(key, 0), because missing really means “seen zero times”:

counts = {}

for topic in ["Lists", "Sets", "Lists"]:
    counts[topic] = counts.get(topic, 0) + 1

print(counts)
{'Lists': 2, 'Sets': 1}

Sets are sticker trays with no duplicates

A set holds each equal, hashable member at most once. It is made for uniqueness, membership, and relationships—not a meaningful display order.

  1. Repeat two equal stickers arrive
  2. Set keeps one equal member
  3. Unique membership stays simple
A set cares whether a value belongs, not where it sits.
tags = {"python", "beginner", "python"}
empty_tags = set()

tags.add("collections")
tags.discard("missing")

print(len(tags))
print("python" in tags)
print(type(empty_tags).__name__)
3
True
set

{} makes an empty dictionary, so an empty set must be set(). remove(x) raises KeyError when x is absent; discard(x) quietly accepts “already gone.”

Set operations answer useful questions:

planned = {"python", "collections", "testing"}
covered = {"python", "collections", "review"}

print((planned | covered) == {"python", "collections", "testing", "review"})
print((planned & covered) == {"python", "collections"})
print((planned - covered) == {"testing"})
print((planned ^ covered) == {"testing", "review"})
print({"python"} <= covered)

All five lines print True. They check union, intersection, difference, symmetric difference, and subset. Compare sets directly; never test them by display order. If you need uniqueness and first-seen order, use a set to remember what appeared and a list to display it.

Tiny project: Study Topic Summary

Create topic_summary.py. This complete program uses only built-in Python collections. Dictionaries describe sessions and count topics; a set removes repeated tags; a list preserves first-seen display order.

sessions = [
    {"topic": "Lists", "minutes": 35, "tags": ("python", "collections")},
    {"topic": "Dictionaries", "minutes": 40, "tags": ("python", "lookup")},
    {"topic": "Lists", "minutes": 25, "tags": ("python", "review")},
]

topic_counts = {}
seen_tags = set()
tag_order = []
total = 0

for session in sessions:
    topic = session["topic"]
    total += session["minutes"]
    topic_counts[topic] = topic_counts.get(topic, 0) + 1

    for tag in session["tags"]:
        if tag not in seen_tags:
            seen_tags.add(tag)
            tag_order.append(tag)

planned = {"python", "collections", "testing"}
missing = planned - seen_tags

print(f"Total: {total} minutes")
for topic, count in topic_counts.items():
    print(f"{topic}: {count} session(s)")
print(f"Tags: {', '.join(tag_order)}")
print(f"Missing planned tags: {len(missing)}")
print(f"Counts correct: {topic_counts == {'Lists': 2, 'Dictionaries': 1}}")

Run python3 topic_summary.py and check:

Total: 100 minutes
Lists: 2 session(s)
Dictionaries: 1 session(s)
Tags: python, collections, lookup, review
Missing planned tags: 1
Counts correct: True

Boundary reminder: every session here has the required keys and numeric minutes. Missing or wrongly typed data needs validation, which arrives in Chapter 10.

Three tiny missions

  1. Zero detective. Use {"Lists": 0} and prove with in that zero and missing are different.
  2. Word counter. Count ['read', 'code', 'read'] with a dictionary and get(word, 0).
  3. Plan comparer. Make planned and finished sets; find finished-both and still-missing topics.

You are ready for Chapter 8 when…

  • you can read, add, update, and intentionally remove dictionary entries;
  • you know that dictionary in checks keys;
  • you can separate a missing key from a stored zero;
  • you can explain why keys and set members must be hashable;
  • you can create an empty set with set() and trust it to keep unique members;
  • you can use the five basic set relationships without relying on order;
  • you can run the Topic Summary and see Counts correct: True.

Next, you will transform these collections with enumerate(), zip(), sorted(), and readable comprehensions.