Python dictionaries and sets

Advanced

Dictionaries look values up by key (phonebook["Mary"]), get() reads safely, in checks for a key; sets drop duplicates automatically. Tally votes with votes[name] = votes.get(name, 0) + 1.

For:Secondary 3 Information & Communication Technology · Unit:Programming II · Lesson 1 of 13 in the learning path

After this lesson, you can:
  • A dictionary stores key-value pairs: find values by key, never by position.
  • Adding and updating share one syntax: d[key] = value; new key adds, old key updates.
  • get() reads safely: a missing key returns your default instead of a KeyError.
文體:編程教學課有聲朗讀

文體小知識:編程教學課每個概念都配一段可以親手試的代碼例子,照住輸入、改一改,最快學會。

資訊及通訊科技Information & Communication Technology

§Text Passage

1A dictionary is Python's structure for storing data in pairs: each pair has a key and a value, just like a real dictionary looks up a meaning by word, or a contacts book finds a number by name. Written as: phonebook = {"Mary": "9123 4567", "John": "6234 7789"}. To find Mary's number, phonebook["Mary"] gives "9123 4567" — no need to remember her position in a list.

2Dictionary operations are intuitive: phonebook["Peter"] = "9876 1234" adds a new contact; assigning to the same key again updates it. The in operator checks whether a key exists: "Mary" in phonebook gives True. To read safely, use phonebook.get("Amy", "no record") — if the key is missing it returns the default text instead of crashing.

3To walk through a dictionary, for name, phone in phonebook.items(): takes out every key-value pair at once. Another handy structure is the set: set(["Mary", "Peter", "Mary"]) gives {"Mary", "Peter"} — duplicates removed automatically, with no order kept. To count how many different names are in a class, one call to set does it.

4A practical use: counting votes for class monitor with a dictionary as tally counter — votes[name] = votes.get(name, 0) + 1, adding one per vote; the key with the largest value wins. Contacts, stock quantities, word counts in an essay — all follow the same pattern: keys as names, values as numbers. Master dictionaries and sets, and handling batches of data becomes much faster.

1Summary 重點摘要

Dictionaries look values up by key (phonebook["Mary"]), get() reads safely, in checks for a key; sets drop duplicates automatically. Tally votes with votes[name] = votes.get(name, 0) + 1.

2Vocabulary cards Vocabulary

D
Dictionary字典

A structure storing data as key-value pairs, finding values by key, like a contacts book.

K
Key鍵

The name used to look up in a dictionary, e.g. "Mary" in {"Mary": "9123 4567"}.

V
Value值

The data a key points to, e.g. the phone number in {"Mary": "9123 4567"}.

K
Key-value pair鍵值對

The basic unit of a dictionary: one key joined to one value by a colon.

g
get()安全取值方法

Fetches by key and returns a default when the key is missing, e.g. d.get("x", 0).

i
items()鍵值對走訪

Returns all key-value pairs so a for loop can take key and value together.

i
in (membership test)成員檢查

Checks whether a key is in a dictionary or an item is in a set, giving True or False.

S
Set集合

An unordered collection with no duplicates, often used to deduplicate, e.g. set([1, 1, 2]) gives {1, 2}.

D
Deduplication去重

Keeping only one copy of each repeated item — the classic use of a set.

3Step by step Steps

  1. Creating a dictionary and reading valuesA dictionary stores data in key-value pairs: student = {"name": "Mary", "class": "3A"}. Read by writing the key in brackets: student["name"] gives "Mary" and student["class"] gives "3A". Unlike a list, a dictionary is indexed by key rather than position, so you never need to remember where the data sits — like a contacts book finding a number by name instead of by slot number. Keys are usually unique strings while values may be of any type, and that flexibility makes the dictionary one of the most used data structures.
  2. Adding and updatingOne syntax, two effects: a new key adds and an existing key updates. student["age"] = 14 adds a new pair; student["class"] = "3B" overwrites the old "3A" with "3B". This uniformity keeps dictionary code minimal: no separate verbs for insert and modify. Note that updating replaces the old value with no trace left; to keep history, store a list as the value and append to it. Modern dictionaries remember insertion order and print accordingly, which keeps the display readable.
  3. Reading safely with get()Reading a missing key directly — student["phone"] — crashes with KeyError; get() stays safe: student.get("phone", "not provided") returns the default text when the key is absent, and the program carries on. The second argument is optional, in which case None is returned. With user input and external data, keys may be missing, so get() is the essential anti-error tool; counting code leans on votes.get(name, 0), treating a first sighting of a name as zero before adding one.
  4. Walking the dictionary and the in checkWalk the whole dictionary with items(): for name, phone in phonebook.items(): print(name, phone) prints each pair such as 'Mary 9123 4567', with items() handing over key and value together. The in operator checks existence: "Mary" in phonebook returns True while "Amy" in phonebook returns False; combined with if: if "Amy" in phonebook: print("found"). Together they build a robust lookup program: check with in first and read the value only when it exists, so KeyError never happens.
  5. Sets remove duplicates automaticallyA set strips out duplicates automatically: set(["Mary", "Peter", "Mary", "Amy"]) leaves {"Mary", "Peter", "Amy"}, only three distinct names. With len(), len(set(names)) is the number of unique names. Sets keep no order, so indexing like scores[0] is impossible; they are the tool for 'unique only, order never' situations — how many different nationalities are in a class, or which distinct answers a survey produced — done in a single step.
  6. A dictionary as tally counterThe dictionary's classic role is the tally counter. For the ballot list votes = ["Mary", "Amy", "Mary"], repeatedly running votes[name] = votes.get(name, 0) + 1 treats the first sighting of "Mary" as 0 plus 1, and later sightings climb from the last count. After all votes, votes = {"Mary": 2, "Amy": 1}. This 'look up the old value, add one, store it back' pattern is universal programming craft — word counts in essays, stock takes and website traffic statistics all run on the same move.
  7. Putting it together: a vote-counting programCombine the pieces into a class-monitor vote counter: start with an empty counter count = {}; for name in votes: processes each ballot, running count[name] = count.get(name, 0) + 1; when counting finishes, max(count, key=count.get) returns the key with the largest value — the winner. Five or six lines perform a real election's tally. Swap the data and the same skeleton counts library loans or canteen favourites; the dictionary counter is the first master key of data processing.

4Diagrams Diagrams

Python 字典:鍵值配對 Dict & setstudent = {"name": "小明", "class": "3A"}student["name"] → "小明"# 鍵 key 揾值 value,好似查字典對比清單:list 用數字位(0,1,2)搵;dict 用名字(鍵)搵——更快更直觀集合 set:{1, 2, 3}——自動剔重複、冇次序,好用嚟「去除重複項」應用:通訊錄(名字→電話)、貨存(貨品→數量)、成績表揀容器:單排數 → list;要「名字搵嘢」→ dict;要剔除重複 → set
Fig. 1: Dictionaries and sets

5Worked example Example

Example: the votes for class monitor are ["Mary", "Amy", "Mary", "Peter", "Mary"]; use a dictionary to tally the votes and find the winner.

  1. Start an empty counter: count = {}.
  2. Walk through the ballots: for name in votes:, taking one name per round.
  3. Add one per vote: count[name] = count.get(name, 0) + 1, with a first sighting counted from 0.
  4. When counting finishes, count = {"Mary": 3, "Amy": 1, "Peter": 1}; max(count, key=count.get) picks the key with the largest value.
  5. Result: Mary wins with 3 votes; check the total with sum(count.values()) = 5.
  6. Answer: The tally is Mary 3, Amy 1, Peter 1, and the winner is the three-vote leader — the core line is count[name] = count.get(name, 0) + 1 with max(count, key=count.get) picking the top key.

6Common mistakes Mistakes

✗ Thinking a dictionary works like a list, reading student[0] for the first item.
✓ Dictionaries look up by key, not position — student[0] only works if 0 happens to be a key; otherwise it raises a KeyError.
✗ Believing reading a missing key just gives None.
✓ student["phone"] with no such key raises a KeyError and stops the program; use get() to read safely.
✗ Trying set[0] to take the first item of a set.
✓ Sets are unordered and do not support indexing; loop with for item in my_set instead.
✗ Expecting set(["Mary", "Mary"]) to keep two Marys.
✓ Deduplication is a set's whole point — the result is just {"Mary"}; keep a list if duplicates matter.
✗ Believing a dictionary sorts itself alphabetically.
✓ A dictionary keeps keys in insertion order and never sorts itself; use sorted() when order matters.

7Quick check Quick check

Q1If phonebook = {"Mary": "9123 4567", "John": "6234 7789"}, what does phonebook["Mary"] give?

Q2What does set([3, 1, 3, 2, 1]) give?

Q3The safest way to read a key that may not exist? A. d["key"] B. d.get("key", 0) C. d.append("key")

Q4What does "Mary" in phonebook check?

Q5votes = {}; running votes[name] = votes.get(name, 0) + 1 three times with names Mary, Amy, Mary — what is votes at the end?

8Recap Recap

  • A dictionary stores key-value pairs: find values by key, never by position.
  • Adding and updating share one syntax: d[key] = value; new key adds, old key updates.
  • get() reads safely: a missing key returns your default instead of a KeyError.
  • in tests whether a key exists; items() lets a for loop take key and value together.
  • A set is unordered and deduplicates automatically; tally votes and word counts with the dictionary counter pattern.

Other subjects in this grade

Same subject, other grades