מילונים, טאפלים וסטיםDicts, tuples & sets
מפתח-ערך, טאפלים בלתי משתנים, סטים בלי כפילויות.
Key-value pairs, immutable tuples, sets without duplicates.
01מילונים: מפתח וערךDictionaries: key and value
מילון שומר זוגות של מפתח וערך. במקום לזכור ש"אינדקס 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.
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)Dune
{'title': 'Dune', 'author': 'Frank Herbert', 'pages': 896, 'rating': 5}
4 Trueצפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מילון הוא כמו ספר טלפונים: מחפשים לפי שם (המפתח) ומקבלים מספר (הערך). אף אחד לא מחפש "את השורה ה-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".
קוראים מפתח שלא קיים.
Reading a key that doesn't exist.
book = {"title": "Dune"}
print(book["rating"])Traceback (most recent call last):
File "/Users/you/python-course/dict.py", line 2, in <module>
print(book["rating"])
~~~~^^^^^^^^^^
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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מילון מחבר מפתח לערך, כמו מילה להסבר שלה.
A dict links a key to a value, like a word to its meaning.
legs = {"cat": 4, "bird": 2}
legs["spider"] = 8
print(legs["bird"])
print(legs.get("fish", 0))
for animal, n in legs.items():
print(animal, n)2 0 cat 4 bird 2 spider 8
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02לעבור על מילוןLooping over a dict
לולאה על מילון נותנת את המפתחות. .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.
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
print(counts)Dune: ⭐⭐⭐⭐⭐
Emma: ⭐⭐⭐⭐
Ulysses: ⭐⭐⭐
{'sci-fi': 3, 'kids': 1, 'classic': 1}צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
.get(x, 0) הוא כמו לשאול "כמה כבר יש לנו מזה? אם עוד אין בכלל, תניח אפס".
.get(x, 0) is like asking "how many of these do we have? If none yet, assume zero".
משנים את גודל המילון בזמן לולאה עליו.
Changing a dict's size while looping over it.
stock = {"Dune": 0, "Emma": 2}
for title in stock:
if stock[title] == 0:
del stock[title]Traceback (most recent call last):
File "/Users/you/python-course/dloop.py", line 2, in <module>
for title in stock:
^^^^^
RuntimeError: dictionary changed size during iterationRuntimeError: 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):.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03רשימה של מילוניםA list of dicts
רוב הנתונים האמיתיים בנויים כרשימה של מילונים: כל פריט הוא מילון עם אותם שדות. ככה תיראה הספרייה שלנו, וככה נראה 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).
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 " "
print(f"[{mark}] {b['title']} ({b['pages']})")
total = sum(b["pages"] for b in shelf if b["read"])
print(total)[✓] Dune (412) [ ] Emma (474) [✓] Matilda (240) 652
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מה קורה עכשיוWhat happens now
פלטOutput
משתנים (frames)Variables (frames)
אובייקטים בזיכרוןObjects in memory
רשימה של מילונים היא כמו קלסר כרטיסים: הקלסר הוא הרשימה, וכל כרטיס הוא מילון עם אותם שדות מודפסים.
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.
מנסים לגשת למילון ברשימה לפי מפתח בלי לבחור קודם פריט.
Accessing a key on the list itself instead of on one item.
shelf = [{"title": "Dune"}]
print(shelf["title"])Traceback (most recent call last):
File "/Users/you/python-course/nested.py", line 2, in <module>
print(shelf["title"])
~~~~~^^^^^^^^^
TypeError: list indices must be integers or slices, not strTypeError: 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"].צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04טאפלים ופירוקTuples and unpacking
טאפל הוא כמו רשימה שאי אפשר לשנות. משתמשים בו לנתונים שהולכים יחד ולא אמורים להשתנות, כמו קואורדינטות. פירוק מחלק טאפל לכמה משתנים בשורה אחת.
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.
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))32.0853 34.7818 Dune יצא ב- 1965 (13, 22)
32.0853 34.7818 Dune came out in 1965 (13, 22)
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
טאפל הוא כמו תאריך לידה בתעודת זהות: מודפס פעם אחת, ואף אחד לא אמור לשנות אותו.
A tuple is like the date of birth on an ID card: printed once, and nobody should change it.
מנסים לשנות טאפל.
Trying to change a tuple.
point = (3, 4)
point[0] = 10Traceback (most recent call last):
File "/Users/you/python-course/tuple.py", line 2, in <module>
point[0] = 10
~~~~~^^^
TypeError: 'tuple' object does not support item assignmentTypeError: '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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05סטים: בלי כפילויותSets: no duplicates
סט שומר כל ערך פעם אחת בלבד, ובלי סדר. הוא מצוין להסרת כפילויות, לבדיקת 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.
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)))['Dune'] ['Dune', 'Emma', 'Matilda', 'Ulysses'] ['Emma', 'Matilda'] 2
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סט הוא כמו רשימת מוזמנים לחתונה: כל שם מופיע פעם אחת, ולא משנה באיזה סדר נרשם.
A set is like a wedding guest list: each name appears once, and the order doesn't matter.
סט ריק כותבים set(). הצורה {} היא מילון ריק.
An empty set is set(). {} is an empty dict.
פונים לסט לפי אינדקס.
Indexing into a set.
tags = {"sci-fi", "kids"}
print(tags[0])Traceback (most recent call last):
File "/Users/you/python-course/sets.py", line 2, in <module>
print(tags[0])
~~~~^^^
TypeError: 'set' object is not subscriptableTypeError: '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].צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
set שומר כל ערך פעם אחת, ויודע למצוא מה משותף.
A set keeps each value once, and can find what's shared.
party1 = {"Noa", "Dan", "Lia"}
party2 = {"Dan", "Ari", "Lia"}
print(sorted(party1 & party2))
print(sorted(party1 | party2))['Dan', 'Lia'] ['Ari', 'Dan', 'Lia', 'Noa']
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06איזה מבנה לבחור?Which structure to choose?
השאלה "איזה מבנה?" מופיעה בכל תוכנית, וגם בכל ראיון עבודה. שאלו: האם הסדר חשוב? האם מחפשים לפי שם? האם הנתונים משתנים? האם מותרות כפילויות?
"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?
| מבנהStructure | סדרOrdered | שינויChangeable | כפילויותDuplicates | דוגמהExample |
|---|---|---|---|---|
list [] | כןYes | כןYes | כןYes | ספרים על המדףBooks on the shelf |
dict {k: v} | כן (לפי הכנסה)Yes (insertion) | כןYes | מפתחות לאKeys no | פרטי ספרA book's details |
tuple () | כןYes | לאNo | כןYes | קואורדינטהA coordinate |
set {} | לאNo | כןYes | לאNo | ז'אנריםGenres |
book = {
"title": "Dune",
"location": (3, 2),
"genres": {"sci-fi", "classic"},
"quotes": ["Fear is the mind-killer."],
}
book["genres"].add("sci-fi")
print(len(book["genres"]), book["location"][0])2 3
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
זה כמו לבחור כלי אחסון בבית: מדף לספרים לפי סדר, מגירה עם תוויות לפי שם, כספת לדברים שלא משתנים, וקופסת "פעם אחת מכל דבר" לאוסף.
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.
משתמשים ברשימה כמפתח במילון. מפתח חייב להיות immutable.
Using a list as a dict key. A key must be immutable.
seats = {}
seats[[3, 2]] = "Dune"Traceback (most recent call last):
File "/Users/you/python-course/choose.py", line 2, in <module>
seats[[3, 2]] = "Dune"
~~~~~^^^^^^^^
TypeError: unhashable type: 'list'TypeError: unhashable type: 'list': משתמשים בטאפל: seats[(3, 2)] = "Dune".TypeError: unhashable type: 'list': use a tuple: seats[(3, 2)] = "Dune".צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.