Programming with Python · free preview

Dictionaries and Sets

Store pairs of data in dictionaries; look values up by key, count with them, and work with sets of unique values.

1. Overview

Overview

2. Looking Things Up by Name

Looking Things Up by Name

3. Adding and Changing Entries

Adding and Changing Entries

4. Looping Over a Dictionary

Looping Over a Dictionary

5. Counting Things

Counting Things

6. Sets of Unique Values

Sets of Unique Values

7. Counting Vowels

Counting Vowels

8. Shared Symptoms

Shared Symptoms

9. Count the items

For colors = ["red", "blue", "red"], what exact dictionary does the .get counting loop produce?

10. Trace a patient record, a vowel counter, and a symptom intersection

Run the program mentally first. Predict the final patient dictionary, the vowel counts, the shared symptom list, and the distinct symptom count. Then run it and compare each printed line with your prediction.

Example. Trace a patient record, a vowel counter, and a symptom intersection

Problem. Run the program mentally first. Predict the final patient dictionary, the vowel counts, the shared symptom list, and the distinct symptom count. Then run it and compare each printed line with your prediction.

Correct solution.

python
patient = {"name": "Alice", "age": 42, "ward": 3}
readings = [37.6, 37.6, 38.5]

word = "inflammation"
vowel_counts = {}
for ch in word:
    if ch in "aeiou":
        vowel_counts[ch] = vowel_counts.get(ch, 0) + 1

morning = {"fever", "chills", "fatigue"}
evening = {"fever", "rash", "fatigue"}

patient["temperature"] = 37.6
patient["age"] = patient["age"] + 1
del patient["ward"]

print(patient)
print(vowel_counts)
print(sorted(morning & evening))
print(len(morning | evening))

Output

{'name': 'Alice', 'age': 43, 'temperature': 37.6}
{'i': 2, 'a': 2, 'o': 1}
['fatigue', 'fever']
4

Trace.

  • patient starts with three keys, then temperature is added, age is overwritten, and ward is deleted.
  • .get(ch, 0) makes the first occurrence of a vowel start at one.
  • & requires both sets, so only fatigue and fever remain.
  • len(morning | evening) counts the union, not the list length with duplicates.

关键提醒。

A dictionary maps names to values and supports fast lookup; a set stores distinct members and supports fast membership plus union, intersection, and difference. The counter pattern is just a dictionary plus a default lookup, and comparisons are clearer when sorted output is printed.

11. Retrieval practice

Given two symptom lists, first = ['fever', 'cough', 'cough'] and second = ['cough', 'rash'], write the two lines that build sets, print every symptom either patient reported, and print the shared symptoms. Give the exact two printed lists.

Use set literals or set(...), and state whether sorted() is necessary for deterministic output.

12. Mastery check

Apply the counting pattern to a new word list, colors = ['red', 'blue', 'red', 'green', 'blue', 'red']. Write the loop that counts with .get, state the exact final dictionary, and name one bug you would catch by asserting that the counts sum to 6.

Answer with the exact dictionary and the assertion expression, not with a prose summary.

Practice this interactively

Free account · instant grading · spaced review that schedules itself.

Start this course for free