נבנה על ידיBuilt by Ariel Yohimovich

חזרה למפגשBack
PythonPython

מילונים, טאפלים וסטיםDicts, tuples & sets

מפגש 8: מפתח-ערך, טאפלים בלתי משתנים, סטים בלי כפילויות.Session 8: Key-value pairs, immutable tuples, sets without duplicates.

מה נעשה היוםToday's plan

  • מילוניםDicts
  • לולאות על מילוןDict loops
  • רשימת מילוניםList of dicts
  • טאפליםTuples
  • סטיםSets
  • בחירת מבנהChoosing
נושא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

אנלוגיה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".

טעות נפוצה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.
נושא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

אנלוגיהAnalogy

.get(x, 0) הוא כמו לשאול "כמה כבר יש לנו מזה? אם עוד אין בכלל, תניח אפס"..get(x, 0) is like asking "how many of these do we have? If none yet, assume zero".

טעות נפוצה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):.
נושא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)

אנלוגיה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.

טעות נפוצה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"].
נושא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
שאלה לכיתה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))

    טאפלים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)

    אנלוגיהAnalogy

    טאפל הוא כמו תאריך לידה בתעודת זהות: מודפס פעם אחת, ואף אחד לא אמור לשנות אותו.A tuple is like the date of birth on an ID card: printed once, and nobody should change it.

    טעות נפוצה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.
    נושא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
    שאלה לכיתהQuestion for the class

    מה ידפיס הקוד?What will this print?

    python
    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)))

      סטיםSets

      sets.py
      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)))
      פלטOutput
      ['Dune']
      ['Dune', 'Emma', 'Matilda', 'Ulysses']
      ['Emma', 'Matilda']
      2

      אנלוגיהAnalogy

      סט הוא כמו רשימת מוזמנים לחתונה: כל שם מופיע פעם אחת, ולא משנה באיזה סדר נרשם.A set is like a wedding guest list: each name appears once, and the order doesn't matter.

      טעות נפוצה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].
      נושאTopic 6

      בחירת מבנהChoosing

      איזה מבנה לבחור?Which structure to choose?

      • רשימה: סדר וכפילויות מותרותList: order, duplicates allowed
      • מילון: חיפוש לפי שםDict: lookup by name
      • טאפל: קבוע, סט: ייחודיTuple: fixed, set: unique

      אנלוגיה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.

      טעות נפוצה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".

      {מפתח: ערך}{key: value}

      d[key] קורא, d[key] = x כותבd[key] reads, d[key] = x writes

      מתאים לרשומה עם שדותGreat for a record with fields

      for k in d: נותן מפתחותfor k in d: gives keys

      .items() נותן זוגות.items() gives pairs

      .get(k, default) בלי KeyError.get(k, default) without KeyError

      רשימה = הרבה רשומותA list = many records

      כל רשומה = מילוןEach record = a dict

      מה למדנו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

      עכשיו לתרגולNow, practice

      5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
      הערות מרצהSpeaker notes

      נבנה על ידיBuilt by Ariel Yohimovich