JSON ו-CSVJSON & CSV
שמירה בפורמטים מקובלים, ייבוא וייצוא.
Saving in standard formats, import and export.
הלוך ושובThere and back
תזכורת: מה ביקשוReminder: the task
שמרו את המילון settings לקובץ settings.json (עם indent=2), טענו אותו לתוך משתנה חדש והדפיסו True אם הם שווים, ואת theme.
Save the dict settings to settings.json (with indent=2), load it into a new variable and print True if they're equal, plus theme.
הפתרון המלא והפלט שלוFull solution and its output
import json
settings = {"theme": "dark", "font": 18, "sound": False}
with open("settings.json", "w", encoding="utf-8") as f:
json.dump(settings, f, indent=2)
with open("settings.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded == settings, loaded["theme"])True dark
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ציונים מ-CSVGrades from CSV
תזכורת: מה ביקשוReminder: the task
הקוד יוצר grades.csv. קראו אותו עם DictReader והדפיסו את הממוצע (מעוגל ל-1) ואת שם התלמיד עם הציון הגבוה ביותר.
The code creates grades.csv. Read it with DictReader and print the average (rounded to 1) and the name of the student with the highest grade.
הפתרון המלא והפלט שלוFull solution and its output
import csv
with open("grades.csv", "w", encoding="utf-8") as f:
f.write("name,grade\nNoa,88\nAvi,95\nDana,79\n")
with open("grades.csv", encoding="utf-8", newline="") as f:
rows = list(csv.DictReader(f))
grades = [int(r["grade"]) for r in rows]
print(round(sum(grades) / len(grades), 1))
print(max(rows, key=lambda r: int(r["grade"]))["name"])87.3 Avi
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
JSON ל-CSVJSON to CSV
תזכורת: מה ביקשוReminder: the task
כתבו json_to_csv(json_path, csv_path) שקוראת רשימת מילונים מ-JSON וכותבת אותה ל-CSV, כשהעמודות הן המפתחות של המילון הראשון. החזירו את מספר השורות שנכתבו.
Write json_to_csv(json_path, csv_path) reading a list of dicts from JSON and writing it to CSV, with the first dict's keys as columns. Return the number of rows written.
הפתרון המלא והפלט שלוFull solution and its output
import csv
import json
def json_to_csv(json_path, csv_path):
with open(json_path, encoding="utf-8") as f:
rows = json.load(f)
with open(csv_path, "w", encoding="utf-8", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
w.writerows(rows)
return len(rows)
with open("in.json", "w", encoding="utf-8") as f:
json.dump([{"title": "Dune", "pages": 412}, {"title": "Emma", "pages": 474}], f)
print(json_to_csv("in.json", "out.csv"))
print(open("out.csv", encoding="utf-8").read().strip())2 title,pages Dune,412 Emma,474
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
טעינה בטוחהSafe loading
תזכורת: מה ביקשוReminder: the task
כתבו safe_load(path, default) שמחזירה את התוכן של קובץ JSON, או את default אם הקובץ לא קיים או פגום (ובמקרה של קובץ פגום מדפיסה broken: <path>).
Write safe_load(path, default) returning a JSON file's content, or default if the file is missing or broken (and for a broken file prints broken: <path>).
הפתרון המלא והפלט שלוFull solution and its output
import json
from pathlib import Path
def safe_load(path, default):
p = Path(path)
if not p.exists():
return default
try:
return json.loads(p.read_text(encoding="utf-8"))
except json.JSONDecodeError:
print(f"broken: {path}")
return default
Path("good.json").write_text("[1, 2]", encoding="utf-8")
Path("bad.json").write_text("[1, 2,", encoding="utf-8")
print(safe_load("good.json", []), safe_load("bad.json", []), safe_load("nope.json", {}))broken: bad.json
[1, 2] [] {}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 21: JSON ויצוא ל-CSVShelf, step 21: JSON and CSV export
תזכורת: מה ביקשוReminder: the task
כתבו save(shelf, path) ו-load(path) ל-JSON (load מחזירה [] אם אין קובץ), ו-export_csv(shelf, path) שכותבת title,author,pages בסדר הזה (ומתעלמת משדות אחרים). שמרו, טענו וייצאו מדף של שני ספרים.
Write save(shelf, path) and load(path) for JSON (load returns [] if there's no file), and export_csv(shelf, path) writing title,author,pages in that order (ignoring other fields). Save, load and export a two-book shelf.
הפתרון המלא והפלט שלוFull solution and its output
import csv
import json
from pathlib import Path
def save(shelf, path):
Path(path).write_text(json.dumps(shelf, indent=2, ensure_ascii=False), encoding="utf-8")
def load(path):
p = Path(path)
return json.loads(p.read_text(encoding="utf-8")) if p.exists() else []
def export_csv(shelf, path):
with open(path, "w", encoding="utf-8", newline="") as f:
w = csv.DictWriter(f, fieldnames=["title", "author", "pages"], extrasaction="ignore")
w.writeheader()
w.writerows(shelf)
shelf = [{"title": "Dune", "author": "Frank Herbert", "pages": 412, "read": 103},
{"title": "הנסיך הקטן", "author": "Antoine de Saint-Exupéry", "pages": 96}]
save(shelf, "shelf.json")
export_csv(load("shelf.json"), "shelf.csv")
print(open("shelf.csv", encoding="utf-8").read().strip())import csv
import json
from pathlib import Path
def save(shelf, path):
Path(path).write_text(json.dumps(shelf, indent=2, ensure_ascii=False), encoding="utf-8")
def load(path):
p = Path(path)
return json.loads(p.read_text(encoding="utf-8")) if p.exists() else []
def export_csv(shelf, path):
with open(path, "w", encoding="utf-8", newline="") as f:
w = csv.DictWriter(f, fieldnames=["title", "author", "pages"], extrasaction="ignore")
w.writeheader()
w.writerows(shelf)
shelf = [{"title": "Dune", "author": "Frank Herbert", "pages": 412, "read": 103},
{"title": "The Little Prince", "author": "Antoine de Saint-Exupéry", "pages": 96}]
save(shelf, "shelf.json")
export_csv(load("shelf.json"), "shelf.csv")
print(open("shelf.csv", encoding="utf-8").read().strip())title,author,pages Dune,Frank Herbert,412 הנסיך הקטן,Antoine de Saint-Exupéry,96
title,author,pages Dune,Frank Herbert,412 The Little Prince,Antoine de Saint-Exupéry,96
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מיזוג רשימותMerging lists
תזכורת: מה ביקשוReminder: the task
שני קבצי CSV של רשימות קריאה (a.csv, b.csv, עמודות title,rating). כתבו merge(paths) שמחזירה רשימת מילונים {title, rating, votes} כאשר rating הוא הממוצע (מעוגל ל-1) של כל הדירוגים לאותה כותרת (בלי רגישות לאותיות ורווחים), ו-votes כמה דירוגים היו. מיינו לפי rating מהגבוה, ואז לפי כותרת.
Two reading-list CSV files (a.csv, b.csv, columns title,rating). Write merge(paths) returning a list of dicts {title, rating, votes} where rating is the average (rounded to 1) of all ratings for that title (ignoring case and spaces), and votes is how many there were. Sort by rating high to low, then by title.
הפתרון המלא והפלט שלוFull solution and its output
import csv
def merge(paths):
seen = {}
for path in paths:
with open(path, encoding="utf-8", newline="") as f:
for r in csv.DictReader(f):
key = r["title"].strip().lower()
entry = seen.setdefault(key, {"title": r["title"].strip(), "ratings": []})
entry["ratings"].append(float(r["rating"]))
out = [{"title": e["title"], "rating": round(sum(e["ratings"]) / len(e["ratings"]), 1), "votes": len(e["ratings"])} for e in seen.values()]
return sorted(out, key=lambda d: (-d["rating"], d["title"]))
with open("a.csv", "w", encoding="utf-8") as f:
f.write("title,rating\nDune,5\nEmma,3\n")
with open("b.csv", "w", encoding="utf-8") as f:
f.write("title,rating\n dune ,4\nMatilda,4.5\n")
for row in merge(["a.csv", "b.csv"]):
print(row){'title': 'Dune', 'rating': 4.5, 'votes': 2}
{'title': 'Matilda', 'rating': 4.5, 'votes': 1}
{'title': 'Emma', 'rating': 3.0, 'votes': 1}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מקודד משלכםYour own encoder
תזכורת: מה ביקשוReminder: the task
כתבו to_json(obj) שממירה כל אובייקט לטיפוסים ש-JSON מכיר, באופן רקורסיבי: dataclass → מילון (asdict), set → רשימה ממוינת, date → isoformat(), מילון → מילון עם ערכים מומרים, רשימה/טאפל → רשימה. השתמשו בה עם json.dumps(..., default=to_json) או ישירות.
Write to_json(obj) that converts any object into JSON-friendly types, recursively: dataclass → dict (asdict), set → sorted list, date → isoformat(), dict → dict with converted values, list/tuple → list. Use it with json.dumps(..., default=to_json) or directly.
הפתרון המלא והפלט שלוFull solution and its output
import json
from dataclasses import dataclass, asdict, is_dataclass
from datetime import date
def to_json(obj):
if is_dataclass(obj):
return to_json(asdict(obj))
if isinstance(obj, dict):
return {k: to_json(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple)):
return [to_json(x) for x in obj]
if isinstance(obj, set):
return sorted(to_json(x) for x in obj)
if isinstance(obj, date):
return obj.isoformat()
return obj
@dataclass
class Book:
title: str
tags: set
added: date
print(json.dumps(to_json([Book("Dune", {"sci-fi", "classic"}, date(2026, 3, 1))])))[{"title": "Dune", "tags": ["classic", "sci-fi"], "added": "2026-03-01"}]יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.