Dicts และ Sets
Dicts — การค้นหาด้วย key อย่างรวดเร็ว
หัวข้อที่มีชื่อว่า “Dicts — การค้นหาด้วย key อย่างรวดเร็ว”dict จับคู่ hashable key กับ value ใด ๆ ตั้งแต่ Python 3.7 ลำดับการแทรก key ได้รับการรับประกันและเก็บรักษาไว้
scores = {'alice': 95, 'bob': 87}scores['carol'] = 92 # เพิ่ม key ใหม่print(scores['alice']) # 95del scores['bob'] # ลบ keyprint(scores) # {'alice': 95, 'carol': 92}การเข้าถึงที่ปลอดภัย: get และ setdefault
หัวข้อที่มีชื่อว่า “การเข้าถึงที่ปลอดภัย: get และ setdefault”การเข้าถึง key ที่ไม่มีด้วย [] จะเกิด KeyError
ใช้ .get() สำหรับการอ่านที่ปลอดภัยพร้อม default ที่กำหนดได้ หรือ .setdefault() เพื่อแทรก default เมื่อ key ไม่มีอยู่
scores = {'alice': 95, 'bob': 87}unknown = scores.get('dave', 0) # คืน 0 — ไม่เกิด KeyErrorscores.setdefault('eve', 88) # แทรก eve=88 เฉพาะเมื่อยังไม่มีprint(scores)# {'alice': 95, 'bob': 87, 'eve': 88}การวนซ้ำด้วย .items()
หัวข้อที่มีชื่อว่า “การวนซ้ำด้วย .items()”.items() ส่งคืน pair (key, value) ที่ unpack ได้โดยตรงใน for loop
for name, score in scores.items(): print(f'{name}: {score}')สามารถวนซ้ำด้วย .keys() (ค่าเริ่มต้น) หรือ .values() แยกกันได้เช่นกัน
Dict comprehensions
หัวข้อที่มีชื่อว่า “Dict comprehensions”เหมือน list comprehension แต่สร้าง dict ใหม่ในนิพจน์เดียว
squared = {n: n**2 for n in range(1, 6)}# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}Sets — element ที่ไม่ซ้ำและ set algebra
หัวข้อที่มีชื่อว่า “Sets — element ที่ไม่ซ้ำและ set algebra”set คือ collection ที่ไม่มีลำดับของ hashable element ที่ไม่ซ้ำกัน
ถูก optimize สำหรับการทดสอบสมาชิกภาพด้วย in (O(1) เฉลี่ย) และรองรับการดำเนินการ set ทางคณิตศาสตร์
a = {1, 2, 3, 4}b = {3, 4, 5, 6}
print(a | b) # union: {1, 2, 3, 4, 5, 6}print(a & b) # intersection: {3, 4}print(a - b) # difference: {1, 2}print(a ^ b) # symmetric diff: {1, 2, 5, 6}ใช้ frozenset สำหรับ set ที่เปลี่ยนแปลงไม่ได้ (hashable ใช้เป็น dict key หรือ set element ได้)
ตัวอย่างรันได้
หัวข้อที่มีชื่อว่า “ตัวอย่างรันได้”# --- dict safe access ---scores = {'alice': 95, 'bob': 87}scores['carol'] = 92print('scores:', scores)
unknown = scores.get('dave', 0)print('dave score:', unknown)
scores.setdefault('eve', 88)print('after setdefault:', scores)
for name, score in scores.items(): print(f' {name}: {score}')
# --- dict comprehension ---squared = {n: n**2 for n in range(1, 6)}print('squared:', squared)
# --- set algebra ---a = {1, 2, 3, 4}b = {3, 4, 5, 6}print('union:', sorted(a | b))print('intersection:', sorted(a & b))print('difference:', sorted(a - b))print('symmetric diff:', sorted(a ^ b))Loading Python runtime (first run only)…