Level: Basic | Prerequisite: Week 6 (Lists, Tuples)
Learning Goals
- Creating dictionaries, accessing keys, modification
- Commonly used methods (
get,items,keys) - Set operations (Union/Intersection/Difference)
- Criteria for choosing data structures
1. What is a dictionary
Mapping of key → value. No order (from 3.7+ insertion order is maintained). Braces {...}.
student = {"name": "Hong Gil-dong", "age": 20, "major": "CS"}
print(student["name"]) #Hong Gil-dong
student["age"] = 21 #Edit
student["email"] = "..." #Add
del student["major"] #Delete
Keys are usually strings or numbers, values can be of any type.
2. Commonly used methods
d = {"a": 1, "b": 2, "c": 3}
print(d.keys()) # dict_keys(['a', 'b', 'c'])
print(d.values()) # dict_values([1, 2, 3])
print(d.items()) # dict_items([('a', 1), ...])
#get: Safe retrieval (no error even if key is missing)
print(d.get("z")) # None
print(d.get("z", "Default value")) #Default value
#in: Check for key existence
print("a" in d) # True
3. Iterating through dictionaries
for key in d: #Only key
print(key)
for key, value in d.items(): #Key-value simultaneously
print(f"{key} = {value}")
4. Sets
Collection of unique elements. No order. Braces {...} (however, empty set is set()).
fruits = {"Apple", "Banana", "Grape"}
fruits.add("Strawberry")
fruits.discard("Banana") #Ignore if not present
print(len(fruits))
#Automatically remove duplicates
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums) # {1, 2, 3}
5. Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) #Union {1,2,3,4,5,6}
print(a & b) #Intersection {3,4}
print(a - b) #Difference {1,2}
print(a ^ b) #Symmetric Difference {1,2,5,6}
6. Criteria for choosing data structures
| Situation | Choice |
|---|---|
| Order matters, access by index | List |
| Unchangeable, fast | Tuple |
| Lookup by key | Dictionary |
| Remove duplicates, check membership | Set |
Key Examples (examples/)
| File | Content |
|---|---|
01_dict_basic.py |
Dictionary Create/Edit |
02_dict_methods.py |
Use get, items, in |
03_set.py |
Set creation and operations |
04_word_count.py |
Word frequency count |
⚠️ Common Mistakes
- Accessing a non-existent key
d = {"a": 1} print(d["z"]) # KeyError
→ Use d.get("z") or if "z" in d:.
-
Create an empty set with
{}s = {} #Empty dictionary! s = set() #Empty set -
Put a list into a set
{[1, 2]} # TypeError: unhashable type: 'list' {(1, 2)} #The tuple is OK -
Modify while iterating over a dictionary
for k in d: del d[k] # RuntimeError
→ Copy the key list in advance: for k in list(d):.
❓ FAQ
Q1. What if dictionary keys are duplicated? A. Overwritten by the last value. Keys must be unique.
Q2. Are dictionaries ordered?
A. From Python 3.7+, insertion order is maintained. Sorting is sorted(d.items()).
Q3. How to distinguish if both sets and dictionaries are {}?
A. If there is :, it’s a dictionary; if not, it’s a set. {1, 2} = set, {1: "a"} = dict.
📝 Exercises (exercises/)
exercise1.md— Contacts (dictionary)exercise2.md— Word frequency Top 3exercise3.md— Remove duplicates (maintain order)
Next Week
Week 8. Handling Strings — Master string methods