חלקPart 1: יסודותFoundations
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
מילונים, טאפלים וסטיםDicts, tuples & sets
מפתח-ערך, טאפלים בלתי משתנים, סטים בלי כפילויות.
Key-value pairs, immutable tuples, sets without duplicates.
הנקודות החשובותKey points
{מפתח: ערך}{key: value}d[key]קורא,d[key] = xכותבd[key]reads,d[key] = xwritesfor k in d:נותן מפתחותfor k in d:gives keys.items()נותן זוגות.items()gives pairs- רשימה = הרבה רשומותA list = many records
- כל רשומה = מילוןEach record = a dict
(a, b)בסוגריים עגולים(a, b)in round brackets- immutable: אי אפשר לשנותImmutable: can't be changed
set(lst)מסיר כפילויותset(lst)removes duplicates
מונחיםTerms
- מילון (dict)dictionary (dict): אוסף של זוגות מפתח-ערך:
{"title": "Dune", "pages": 412}. ניגשים לפי מפתח, לא לפי מקום.A collection of key-value pairs:{"title": "Dune", "pages": 412}. Access by key, not position. - מפתחkey: השם שלפיו מוצאים ערך במילון. חייב להיות immutable (מחרוזת, מספר, טאפל).The name used to find a value in a dict. Must be immutable (string, number, tuple).
- טאפל (tuple)tuple: רצף בסוגריים עגולים שאי אפשר לשנות:
(32.08, 34.78).A sequence in parentheses that can't be changed:(32.08, 34.78). - פירוק (unpacking)unpacking: חלוקת רצף לכמה משתנים בבת אחת:
lat, lon = point.Splitting a sequence into several variables at once:lat, lon = point. - סט (set)set: אוסף בלי סדר ובלי כפילויות:
{"sci-fi", "kids"}. בדיקתinמהירה מאוד.An unordered collection with no duplicates:{"sci-fi", "kids"}.inchecks are very fast.
Cheatsheet
מילוניםDicts
book = {"title": "Dune", "author": "Frank Herbert", "pages": 412}
print(book["title"])
book["rating"] = 5
book["pages"] = 896
print(book)
print(len(book), "author" in book)לולאות על מילוןDict loops
ratings = {"Dune": 5, "Emma": 4, "Ulysses": 3}
for title, stars in ratings.items():
print(f"{title}: {'⭐' * stars}")
genres = ["sci-fi", "kids", "sci-fi", "classic", "sci-fi"]
counts = {}
for g in genres:
counts[g] = counts.get(g, 0) + 1רשימת מילוניםList of dicts
shelf = [
{"title": "Dune", "pages": 412, "read": True},
{"title": "Emma", "pages": 474, "read": False},
]
shelf.append({"title": "Matilda", "pages": 240, "read": True})
for b in shelf:
mark = "✓" if b["read"] else " "טאפליםTuples
library = (32.0853, 34.7818)
lat, lon = library
print(lat, lon)
book = ("Dune", 1965)
title, year = book
print(f"{title} יצא ב- {year}")
print(divmod(412, 30))library = (32.0853, 34.7818)
lat, lon = library
print(lat, lon)
book = ("Dune", 1965)
title, year = book
print(f"{title} came out in {year}")
print(divmod(412, 30))סטיםSets
noa = {"Dune", "Emma", "Matilda"}
dan = {"Dune", "Ulysses"}
print(sorted(noa & dan))
print(sorted(noa | dan))
print(sorted(noa - dan))
tags = ["sci-fi", "kids", "sci-fi"]
print(len(set(tags)))בחירת מבנהChoosing
book = {
"title": "Dune",
"location": (3, 2),
"genres": {"sci-fi", "classic"},
"quotes": ["Fear is the mind-killer."],
}
book["genres"].add("sci-fi")שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
KeyError | קוראים מפתח שלא קיים.Reading a key that doesn't exist. | KeyError: 'rating': בודקים עם in, או book.get("rating") שמחזירה None, או book.get("rating", 0) עם ברירת מחדל.KeyError: 'rating': check with in, or use book.get("rating") (returns None) or book.get("rating", 0) with a default. |
RuntimeError | משנים את גודל המילון בזמן לולאה עליו.Changing a dict's size while looping over it. | RuntimeError: dictionary changed size during iteration: עוברים על עותק: for title in list(stock):.RuntimeError: dictionary changed size during iteration: loop over a copy: for title in list(stock):. |
TypeError | מנסים לגשת למילון ברשימה לפי מפתח בלי לבחור קודם פריט.Accessing a key on the list itself instead of on one item. | TypeError: list indices must be integers or slices, not str: קודם פריט, אחר כך מפתח: shelf[0]["title"].TypeError: list indices must be integers or slices, not str: item first, then key: shelf[0]["title"]. |
TypeError | מנסים לשנות טאפל.Trying to change a tuple. | TypeError: 'tuple' object does not support item assignment: יוצרים טאפל חדש, או משתמשים ברשימה אם הנתונים אמורים להשתנות.TypeError: 'tuple' object does not support item assignment: make a new tuple, or use a list if the data should change. |
TypeError | פונים לסט לפי אינדקס.Indexing into a set. | TypeError: 'set' object is not subscriptable: לסט אין סדר. ממירים לרשימה: sorted(tags)[0].TypeError: 'set' object is not subscriptable: a set has no order. Convert to a list: sorted(tags)[0]. |
TypeError | משתמשים ברשימה כמפתח במילון. מפתח חייב להיות immutable.Using a list as a dict key. A key must be immutable. | TypeError: unhashable type: 'list': משתמשים בטאפל: seats[(3, 2)] = "Dune".TypeError: unhashable type: 'list': use a tuple: seats[(3, 2)] = "Dune". |