מפגש 8: מפתח-ערך, טאפלים בלתי משתנים, סטים בלי כפילויות.Session 8: Key-value pairs, immutable tuples, sets without duplicates.
מפתח-ערך, טאפלים בלתי משתנים, סטים בלי כפילויות. בסוף המפגש מוסיפים צעד לפרויקט המלווה.Key-value pairs, immutable tuples, sets without duplicates. At the end we add a step to the companion project.
מה נעשה היוםToday's plan
מילוניםDicts
לולאות על מילוןDict loops
רשימת מילוניםList of dicts
טאפליםTuples
סטיםSets
בחירת מבנהChoosing
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.
נושאTopic 1
מילוניםDicts
מילונים: מפתח וערךDictionaries: key and value
{מפתח: ערך}{key: value}
d[key] קורא, d[key] = x כותבd[key] reads, d[key] = x writes
מתאים לרשומה עם שדותGreat for a record with fields
מילון שומר זוגות של מפתח וערך. במקום לזכור ש"אינדקס 2 הוא מספר העמודים", נותנים לכל שדה שם. ככה ספר אחד בפרויקט שלנו נהיה מילון אחד.A dictionary (dict) stores pairs of key and value. Instead of remembering that "index 2 is the page count", each field gets a name. That way one book in our project becomes one dict.
אנלוגיהAnalogy
מילון הוא כמו ספר טלפונים: מחפשים לפי שם (המפתח) ומקבלים מספר (הערך). אף אחד לא מחפש "את השורה ה-37".A dict is like a phone book: you look up a name (the key) and get a number (the value). Nobody looks up "line 37".
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
dict.py
book = {"title":"Dune"}
print(book["rating"])
מה Python עונהWhat Python says
KeyError: 'rating'
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.
קוראים מפתח שלא קיים.Reading a key that doesn't exist.
נושאTopic 2
לולאות על מילוןDict loops
לעבור על מילוןLooping over a dict
for k in d: נותן מפתחותfor k in d: gives keys
.items() נותן זוגות.items() gives pairs
.get(k, default) בלי KeyError.get(k, default) without KeyError
לולאה על מילון נותנת את המפתחות. .items() נותנת זוגות (מפתח, ערך), ו-.values() רק ערכים. דפוס שימושי במיוחד: ספירה עם counts[x] = counts.get(x, 0) + 1.Looping over a dict gives the keys. .items() gives (key, value) pairs, and .values() just values. A very useful pattern: counting with counts[x] = counts.get(x, 0) + 1.
אנלוגיהAnalogy
.get(x, 0) הוא כמו לשאול "כמה כבר יש לנו מזה? אם עוד אין בכלל, תניח אפס"..get(x, 0) is like asking "how many of these do we have? If none yet, assume zero".
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
dloop.py
stock = {"Dune":0, "Emma":2}
for title in stock:if stock[title] ==0:del stock[title]
מה Python עונהWhat Python says
RuntimeError: dictionary changed size during iteration
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):.
משנים את גודל המילון בזמן לולאה עליו.Changing a dict's size while looping over it.
נושאTopic 3
רשימת מילוניםList of dicts
רשימה של מילוניםA list of dicts
רשימה = הרבה רשומותA list = many records
כל רשומה = מילוןEach record = a dict
ככה נראים רוב הנתונים בעולם (JSON)Most real data looks like this (JSON)
רוב הנתונים האמיתיים בנויים כרשימה של מילונים: כל פריט הוא מילון עם אותם שדות. ככה תיראה הספרייה שלנו, וככה נראה JSON שמגיע מאתרים (מפגש 21).Most real data is a list of dicts: each item is a dict with the same fields. Our library will look like this, and so does JSON from websites (session 21).
אנלוגיהAnalogy
רשימה של מילונים היא כמו קלסר כרטיסים: הקלסר הוא הרשימה, וכל כרטיס הוא מילון עם אותם שדות מודפסים.A list of dicts is like a card file: the box is the list and each card is a dict with the same printed fields.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
nested.py
shelf = [{"title":"Dune"}]
print(shelf["title"])
מה Python עונהWhat Python says
TypeError: list indices must be integers or slices, not str
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"].
מנסים לגשת למילון ברשימה לפי מפתח בלי לבחור קודם פריט.Accessing a key on the list itself instead of on one item.
נושאTopic 4
טאפליםTuples
טאפלים ופירוקTuples and unpacking
(a, b) בסוגריים עגולים(a, b) in round brackets
immutable: אי אפשר לשנותImmutable: can't be changed
פירוק: x, y = pointUnpacking: x, y = point
טאפל הוא כמו רשימה שאי אפשר לשנות. משתמשים בו לנתונים שהולכים יחד ולא אמורים להשתנות, כמו קואורדינטות. פירוק מחלק טאפל לכמה משתנים בשורה אחת.A tuple is like a list that can't change. Use it for data that belongs together and shouldn't change, like coordinates. Unpacking splits a tuple into several variables in one line.
שאלה לכיתהQuestion for the class
מה ידפיס הקוד?What will this print?
python
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))
נותנים לכיתה חצי דקה לנחש, ואז עוברים לשקופית הבאה.Give the class half a minute to guess, then move on.
טאפליםTuples
tuple.py
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))
פלטOutput
32.0853 34.7818
Dune יצא ב- 1965
(13, 22)
32.0853 34.7818
Dune came out in 1965
(13, 22)
מריצים ומשווים לניחושים.Run it and compare with the guesses.
אנלוגיהAnalogy
טאפל הוא כמו תאריך לידה בתעודת זהות: מודפס פעם אחת, ואף אחד לא אמור לשנות אותו.A tuple is like the date of birth on an ID card: printed once, and nobody should change it.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
tuple.py
point = (3, 4)
point[0] =10
מה Python עונהWhat Python says
TypeError: 'tuple' object does not support item assignment
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.
מנסים לשנות טאפל.Trying to change a tuple.
נושאTopic 5
סטיםSets
סטים: בלי כפילויותSets: no duplicates
set(lst) מסיר כפילויותset(lst) removes duplicates
a & b משותף, a | b איחודa & b common, a | b union
a - b מה שרק ב-aa - b only in a
סט שומר כל ערך פעם אחת בלבד, ובלי סדר. הוא מצוין להסרת כפילויות, לבדיקת in מהירה, ולהשוואת קבוצות: מה משותף, מה האיחוד, מה ההבדל.A set keeps each value once, with no order. It's great for removing duplicates, fast in checks, and comparing groups: what's common, the union, the difference.
מריצים ומשווים לניחושים.Run it and compare with the guesses.
אנלוגיהAnalogy
סט הוא כמו רשימת מוזמנים לחתונה: כל שם מופיע פעם אחת, ולא משנה באיזה סדר נרשם.A set is like a wedding guest list: each name appears once, and the order doesn't matter.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
sets.py
tags = {"sci-fi", "kids"}
print(tags[0])
מה Python עונהWhat Python says
TypeError: 'set' object is not subscriptable
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].
פונים לסט לפי אינדקס.Indexing into a set.
נושאTopic 6
בחירת מבנהChoosing
איזה מבנה לבחור?Which structure to choose?
רשימה: סדר וכפילויות מותרותList: order, duplicates allowed
מילון: חיפוש לפי שםDict: lookup by name
טאפל: קבוע, סט: ייחודיTuple: fixed, set: unique
השאלה "איזה מבנה?" מופיעה בכל תוכנית, וגם בכל ראיון עבודה. שאלו: האם הסדר חשוב? האם מחפשים לפי שם? האם הנתונים משתנים? האם מותרות כפילויות?"Which structure?" comes up in every program and in every job interview. Ask: does order matter? Do I look things up by name? Does the data change? Are duplicates allowed?
אנלוגיהAnalogy
זה כמו לבחור כלי אחסון בבית: מדף לספרים לפי סדר, מגירה עם תוויות לפי שם, כספת לדברים שלא משתנים, וקופסת "פעם אחת מכל דבר" לאוסף.It's like choosing storage at home: a shelf for books in order, labelled drawers by name, a safe for things that don't change, and a "one of each" box for a collection.
שואלים אם מישהו מכיר דוגמה נוספת מהחיים.Ask for another real-life example.
טעות נפוצהCommon mistake
choose.py
seats = {}
seats[[3, 2]] ="Dune"
מה Python עונהWhat Python says
TypeError: unhashable type: 'list'
TypeError: unhashable type: 'list': משתמשים בטאפל: seats[(3, 2)] = "Dune".TypeError: unhashable type: 'list': use a tuple: seats[(3, 2)] = "Dune".
משתמשים ברשימה כמפתח במילון. מפתח חייב להיות immutable.Using a list as a dict key. A key must be immutable.
{מפתח: ערך}{key: value}
מילונים: מפתח וערךDictionaries: key and value
d[key] קורא, d[key] = x כותבd[key] reads, d[key] = x writes
מילונים: מפתח וערךDictionaries: key and value
מתאים לרשומה עם שדותGreat for a record with fields
מילונים: מפתח וערךDictionaries: key and value
for k in d: נותן מפתחותfor k in d: gives keys
לעבור על מילוןLooping over a dict
.items() נותן זוגות.items() gives pairs
לעבור על מילוןLooping over a dict
.get(k, default) בלי KeyError.get(k, default) without KeyError
לעבור על מילוןLooping over a dict
רשימה = הרבה רשומותA list = many records
רשימה של מילוניםA list of dicts
כל רשומה = מילוןEach record = a dict
רשימה של מילוניםA list of dicts
מה למדנוWhat we learned
{מפתח: ערך}{key: value}
for k in d: נותן מפתחותfor k in d: gives keys
רשימה = הרבה רשומותA list = many records
(a, b) בסוגריים עגולים(a, b) in round brackets
set(lst) מסיר כפילויותset(lst) removes duplicates
רשימה: סדר וכפילויות מותרותList: order, duplicates allowed
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.
עכשיו לתרגולNow, practice
5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked