Module 4b

Collection Data Types — Tuple, Set, Dictionary

วันนี้เราจะเรียนรู้ 🚀

  1. ทูเพิล (Tuple)
  2. เซ็ต (Set)
  3. ดิกชันนารี (Dictionary)
  4. Collection of Collections
students = [
    {"name": "Somchai", "gpa": 3.75},
    {"name": "Somying", "gpa": 3.50},
]
avg = sum(s["gpa"] for s in students) / len(students)
print(f"Average GPA: {avg:.2f}")

Tuple 📦

ทูเพิล — เก็บข้อมูลเหมือน List แต่แก้ไขไม่ได้

ทูเพิล (Tuple) คืออะไร?

  • เก็บข้อมูลในลักษณะเดียวกันกับลิสต์ แต่ไม่สามารถเปลี่ยนแปลงค่าได้ (immutable)
  • ใช้เครื่องหมาย () สร้าง tuple โดยคั่นข้อมูลด้วย ,
tuple_variable = (item1, item2, item3, ...)
tup0 = ()
print(tup0)
()
tup1 = (555,)
print(tup1)
(555,)
tup2 = (100,200,2.5,3.5,'hello')
print(tup2)
(100, 200, 2.5, 3.5, 'hello')
print(type(tup2))
<class 'tuple'>

โจทย์ #21

สร้าง tuple แล้วเข้าถึงข้อมูลด้วย index ได้เหมือน List

tup = (100,200,300,400,500,2.5,3.5,4.5,'hello')
print(tup[4])
print(tup[0]+tup[4])
print(tup[-1])
500
600
hello

Tuple — len() และ Slice

สามารถใช้ len() และ slice ได้เหมือน List

tup = (100, 200, 300, 400, 500, 2.5, 3.5, 4.5, 'hello')
print(len(tup))
9
print(tup[0:4])
(100, 200, 300, 400)
print(tup[:10:3])     # start=0, stop=10, step=3
(100, 400, 3.5)

โจทย์ #22: ชวนคิด

Tuple ไม่รองรับการแก้ไข — ถ้าลองแล้วจะเกิดอะไรขึ้น?

tup = (100,200,300,400,500,2.5,3.5,4.5,'hello')
tup[0] = 1000
TypeError: 'tuple' object does not support item assignment

Important

Tuple เป็น immutable — ไม่สามารถแก้ไขข้อมูลภายในได้!

การแปลงค่าระหว่าง Tuple และ List

ฟังก์ชัน ผลลัพธ์
list(tuple_var) แปลง Tuple → List
tuple(list_var) แปลง List → Tuple

Note

ทบทวน: Type Conversion (Module 3)list() และ tuple() ทำงานคล้าย int(), float(), str()

โจทย์ #23

แปลง Tuple เป็น List เพื่อแก้ไข แล้วแปลงกลับเป็น Tuple

x = ("apple", "banana", "cherry")
print(type(x), x)

# แปลง tuple เป็น list
y = list(x)
print(type(y), y)

# แก้ไข list
y[1] = "kiwi"
y.append("orange")

# แปลง list เป็น tuple
z = tuple(y)
print(type(z), z)
<class 'tuple'> ('apple', 'banana', 'cherry')
<class 'list'> ['apple', 'banana', 'cherry']
<class 'tuple'> ('apple', 'kiwi', 'cherry', 'orange')

Set 🎲

เซ็ต — ชุดข้อมูลที่ไม่ซ้ำกัน ไม่มีลำดับ

เซ็ต (Set) คืออะไร?

  • ใช้จัดเก็บชุดข้อมูลสำหรับประมวลผลแบบเซ็ตในทางคณิตศาสตร์
  • ใช้ {} สร้าง set โดยคั่นข้อมูลด้วย ,
  • ไม่สามารถเก็บข้อมูลซ้ำกันได้ (unique)
  • ไม่รองรับการอ้างอิงด้วย index (ไม่มีลำดับ — unordered)
  • รองรับ union, intersection, -

สร้าง set — ข้อมูลซ้ำถูกตัดออก

a = {1,2,2,3,3,5,8}
print(a)
{1, 2, 3, 5, 8}

Important

empty set สร้างโดยใช้ set() ไม่ใช่ {}

Empty set — เซตว่าง

x = set()   # empty set
print(type(x))
<class 'set'>

Empty dictionaryดิกชันนารีว่าง 👉

x = {}        # นี่คือ dict!
print(type(x))
<class 'dict'>

โจทย์ #24

สร้าง set แล้วสังเกตว่าข้อมูลที่ซ้ำกันจะถูกตัดออก

คิดก่อน: b จะมีสมาชิกกี่ตัว?

b = {1,2,'hello','hello','Hello',3.78}
print(b)
print(len(b))    # ใช้ len() กับ set ก็ได้
{1, 2, 3.78, 'Hello', 'hello'}
5

Set Operations

Union — รวมสมาชิกทั้งหมด

\[A \cup B\]

c = a.union(b)
d = a | b

Intersection — เฉพาะสมาชิกร่วม

\[A \cap B\]

c = a.intersection(b)
d = a & b

Difference — อยู่ใน a แต่ไม่อยู่ใน b

\[A - B\]

c = a.difference(b)
d = a - b

Subseta อยู่ใน b ทั้งหมดหรือไม่

\[A \subseteq B\]

c = a.issubset(b)
d = a <= b

โจทย์ #25

หา union และ intersection ของ set a และ b

a = {1,2,2,3,3,5,8}
b = {1,2,'hello','hello','Hello',3.78}
c = a.union(b)   # a union b
d = a | b    # a union b
print(f'c = {c}')
print(f'd = {d}')
c = a.intersection(b)
d = a & b
print(f'c = {c}')
print(f'd = {d}')
c = {1, 2, 3, 3.78, 5, 8, 'Hello', 'hello'}
d = {1, 2, 3, 3.78, 5, 8, 'Hello', 'hello'}
c = {1, 2}
d = {1, 2}

ตัวอย่าง: ผลต่างของ Set (-)

หาผลต่าง a-b และ b-a — ผลลัพธ์ไม่เหมือนกัน

a = {1,2,2,3,3,5,8}
b = {1,2,'hello','hello','Hello',3.78}
print(f'a-b: {a-b}')
print(f'b-a: {b-a}')
a-b: {3, 5, 8}
b-a: {3.78, 'Hello', 'hello'}

ตัวอย่าง: subset — .issubset()

ตรวจสอบว่า set z เป็น subset ของ a หรือไม่

a = {1,2,2,3,3,5,8}
z = {3,5}
print(z.issubset(a))  # z เป็น subset ของ a? True
print(a.issubset(z))  # a เป็น subset ของ z? False
True
False

โจทย์ #26: ชวนคิด

Set ไม่รองรับการอ้างอิงด้วย index และไม่รองรับการแก้ไขค่าโดยตรง — ลองแล้วจะเกิดอะไร?

a = {1,2,3,5,8}
print(a[3])
TypeError: 'set' object is not subscriptable
a[3] = 100
TypeError: 'set' object does not support item assignment

Important

Set ไม่มี index — ไม่สามารถอ้างอิงหรือแก้ไขด้วย [] ได้!

การเพิ่มข้อมูลและลบข้อมูลใน Set

วิธี คำอธิบาย
.add(x) เพิ่มข้อมูลทีละตัว (รับค่าที่จะใส่เพิ่ม)
.update(set2) เพิ่มข้อมูลจาก set อื่น (รับ set ที่จะใส่เพิ่ม)
.remove(x) ลบ x (error ถ้าไม่มี)
.discard(x) ลบ x (ไม่ error ถ้าไม่มี)
.clear() ลบทั้งหมด

Note

คำสั่งกลุ่มนี้แก้ไข set ต้นฉบับโดยตรง (in-place) และคืนค่า None — ต่างจาก .union(), .intersection(), .difference() ที่ไม่แก้ต้นฉบับ แต่คืน set ใหม่ออกมา

โจทย์ #27

ใช้ .add() และ .update() เพิ่มข้อมูลใน set

โค้ดต่อไปนี้พิมพ์อะไรออกมา?

a = {1,2,2,3,3,5,8}
a.add(10)
print(a)

a.update({100,200,300})
print(a)
{1, 2, 3, 5, 8, 10}
{1, 2, 3, 5, 8, 10, 100, 200, 300}

โจทย์ #28

ใช้ .remove() และ .discard() ลบข้อมูลจาก set

คิดก่อน: .remove() กับ .discard() ต่างกันอย่างไร เมื่อค่าที่จะลบไม่มีอยู่?

a = {1, 2, 3, 5, 8, 10, 100, 200, 300}
a.remove(100)
print(a)
{1, 2, 3, 5, 8, 10, 200, 300}
a.remove(1000)  # → KeyError: 1000
a.discard(1000)  # ไม่ error!
print(a)
{1, 2, 3, 5, 8, 10, 200, 300}

Tip

.discard() ปลอดภัยกว่า .remove() — ไม่ error เมื่อค่าไม่มีอยู่

ตัวอย่าง: .clear() — ลบทั้งหมด

a = {1, 2, 3, 5, 8, 10, 200, 300}
print(f'a = {a}')

a.clear()
print(f'a = {a}')
a = {1, 2, 3, 5, 8, 10, 200, 300}
a = set()

Dictionary 📖

ดิกชันนารี — เก็บข้อมูลด้วย key แทน index

ดิกชันนารี (Dictionary) คืออะไร?

  • เก็บข้อมูลเป็น item คล้าย List แต่ใช้ key ในการอ้างอิงแทน index ตัวเลข
  • ค่า key สามารถเป็น int, float, string, tuple ก็ได้ (แต่ list เป็น key ไม่ได้)
  • ค่า key เมื่อกำหนดแล้ว จะไม่สามารถเปลี่ยนแปลงได้ (หมายถึงเพิ่มหรือลบ key ได้ แต่ rename ไม่ได้)
dict_variable = {key1: value1, key2: value2, ...}

หรือจะเขียนสวย ๆ

dict_variable = {
    key1: value1,
    key2: value2,
    ...
}

โจทย์ #29

ให้สร้าง dictionary เก็บข้อมูลนักเรียนตามตารางต่อไปนี้

key value
"name" "Harry Potter"
999 "085-123-4567"
"isMale" True
"midterm" 25
"final" 30
person = {"name":"Harry Potter",999:"085-123-4567","isMale":True,"midterm":25,"final":30}
print(person)
print(type(person))
{'name': 'Harry Potter', 999: '085-123-4567', 'isMale': True, 'midterm': 25, 'final': 30}
<class 'dict'>

การเข้าถึงข้อมูลภายใน Dict ด้วย key

ใช้ key อ้างอิงแทน index ตัวเลข

dict_variable[key]
person2 = {"name":"Harry Potter", "isMale": True, "midterm":25, "final":30}
print(person2["name"])      # เข้าถึงค่าด้วย key "name"
print(person2["final"])     # เข้าถึงค่าด้วย key "final"
Harry Potter
30

Important

ถ้าอ้างอิง key ที่ไม่มีอยู่ จะเกิด KeyError

โจทย์ #30

ดึงข้อมูลจาก dict ด้วย key แล้วนำมาคำนวณคะแนนรวม midterm+final และพิมพ์ข้อความ

Harry Potter got 55/100 in Python programming.
person = {"name":"Harry Potter", "isMale": True, "midterm":25, "final":30}
name = person["name"]
score = person["midterm"] + person["final"]
print(f'{name} got {score}/100 in Python programming.')
Harry Potter got 55/100 in Python programming.

Note

ทบทวน: f-string (Module 3)

ตัวอย่าง: แก้ไขค่าใน Dict ด้วย key

แก้ไข value ของ keyword "name"

person = {
    "name":"Harry Potter", 
    "isMale": True, 
    "midterm":25, 
    "final":30
}
person["name"] = "Rionel Messi"
print(person)
{'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30}

โจทย์ #31: ชวนคิด

ดึงข้อมูลด้วย key ที่ไม่มีอยู่ใน dict จะเกิดอะไรขึ้น?

person2 = {"name":"Rionel Messi", "isMale": True, "midterm":25, "final":30}
print(person2["address"])
KeyError: 'address'

Important

ดึงข้อมูลด้วย key ที่ไม่มี → KeyError

การเพิ่มข้อมูลให้กับ Dict

เพิ่ม item ใหม่ด้วยการกำหนดค่าให้ key ที่ไม่เคยมีมาก่อน

dict_variable[new_key] = value

Important

dict_variable[key] = value — ถ้า key ยังไม่มี จะเป็นการสร้าง item ใหม่ แต่ถ้า key มีอยู่แล้ว จะเป็นการแก้ไขค่าเดิม

โจทย์ #32

เพิ่มข้อมูล "weight" และ "height" ให้กับ dict

ข้อมูลเดิม

key value
"name" "Rionel Messi"
"isMale" True
"midterm" 25
"final" 30

ข้อมูลที่ต้องการเพิ่ม

key value
"weight" 65.25
"height" 180.0
person2 = {"name":"Rionel Messi", "isMale": True, "midterm":25, "final":30}
print(person2)
person2["weight"] = 65.25
person2["height"] = 180.0
print(person2)
{'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30}
{'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30, 'weight': 65.25, 'height': 180.0}

อีกวิธี: เพิ่มหลาย item ด้วย .update()

.update() เพิ่ม (หรือแก้ไข) หลาย item พร้อมกันในครั้งเดียว โดยรับ dict อีกตัวเข้าไป — เป็น method เดียวกับ .update() ของ set ที่เคยเรียนมา

person2 = {"name":"Rionel Messi", "isMale": True, "midterm":25, "final":30}
person2.update({"weight": 65.25, "height": 180.0})
print(person2)
{'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30, 'weight': 65.25, 'height': 180.0}

Note

ได้ผลลัพธ์เหมือนโจทย์ #32 แต่เขียนบรรทัดเดียว — ถ้า key มีอยู่แล้วจะเป็นการแก้ไขค่าเดิม เหมือน dict_variable[key] = value

Dict — len()

len() นับจำนวน item (จำนวน key) ใน Dict

person2 = {'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30, 'weight': 65.25, 'height': 180.0}
print(person2)
print(f'len(person2): {len(person2)}')
{'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30, 'weight': 65.25, 'height': 180.0}
len(person2): 6

การดูข้อมูลภายใน Dict

Dict มี method สำหรับดึงรายการข้อมูลออกมาดู 3 แบบ

วิธี คืนค่า
.keys() รายการ key ทั้งหมด
.values() รายการ value ทั้งหมด
.items() รายการ (key, value) ทั้งหมด (Tuple)

Tip

นำผลลัพธ์ไปครอบด้วย list() เพื่อแปลงเป็น List ปกติได้

การดูรายการ key ทั้งหมด — .keys()

dict_variable.keys()

ตัวอย่าง: ดึง key ทั้งหมด

person2 = {'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30, 'weight': 65.25, 'height': 180.0}
person2_keys = person2.keys()
print(person2_keys)
print(list(person2_keys))
dict_keys(['name', 'isMale', 'midterm', 'final', 'weight', 'height'])
['name', 'isMale', 'midterm', 'final', 'weight', 'height']

การดูรายการ value ทั้งหมด — .values()

dict_variable.values()

ตัวอย่าง: ดึง value ทั้งหมด

person2 = {'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30, 'weight': 65.25, 'height': 180.0}
person2_values = person2.values()
print(person2_values)
print(list(person2_values))
dict_values(['Rionel Messi', True, 25, 30, 65.25, 180.0])
['Rionel Messi', True, 25, 30, 65.25, 180.0]

การดูรายการข้อมูลทั้งหมด — .items()

.items() แสดงรายการข้อมูลทั้งหมดใน Dict ในรูปแบบ List ของ Tuple

[(key1, value1), (key2, value2), ..., (keyN, valueN)]

ตัวอย่าง: ดึงข้อมูลทั้งหมด

person2 = {'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30, 'weight': 65.25, 'height': 180.0}
person2_items = person2.items()
print(person2_items)
print(list(person2_items))
dict_items([('name', 'Rionel Messi'), ('isMale', True), ('midterm', 25), ('final', 30), ('weight', 65.25), ('height', 180.0)])
[('name', 'Rionel Messi'), ('isMale', True), ('midterm', 25), ('final', 30), ('weight', 65.25), ('height', 180.0)]

การลบข้อมูลจาก Dict

วิธี คำอธิบาย
.pop(key) ลบข้อมูลด้วย key ที่ระบุ
.popitem() ลบ item ที่เพิ่มล่าสุด
.clear() ลบข้อมูลทั้งหมด

Note

ตั้งแต่ Python 3.7 เป็นต้นมา Dict จำลำดับการเพิ่มข้อมูล (insertion order) — ต่างจาก Set ที่ไม่มีลำดับ ดังนั้น .popitem() จึงลบตัวที่เพิ่มเข้าไปล่าสุดออกได้เสมอ

โจทย์ #33

ใช้ .pop() ดึง keyword "height" ออกจาก dict และเก็บค่าที่ดึงออกมาลงในตัวแปร height โดยที่ dict ต้นฉบับจะต้องไม่มี keyword "height" เหลืออยู่

d1 = {'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30, 'weight': 65.25, 'height': 180.0}
print(d1)

height = d1.pop('height')
print(d1)
print(height)
{'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30, 'weight': 65.25, 'height': 180.0}
{'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30, 'weight': 65.25}
180.0

โจทย์ #34: ชวนคิด

.pop() ด้วย key ที่ไม่มี หรือไม่ระบุ key จะเกิดอะไร?

c = d1.pop('team')
KeyError: 'team'
b = d1.pop()
TypeError: pop expected at least 1 argument, got 0

Important

Dict .pop() ต้องระบุ key เสมอ! (ต่างจาก List .pop() ที่ไม่ระบุได้)

ตัวอย่าง: .popitem() และ .clear()

d1 = {'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30, 'weight': 65.25}

thing = d1.popitem()
print(d1)
print(thing)

d1.clear()
print(d1)
{'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30, 'weight': 65.25}
{'name': 'Rionel Messi', 'isMale': True, 'midterm': 25, 'final': 30}
('weight', 65.25)
{}

Tip

.popitem() ลบ 'weight' (key ที่อยู่ท้ายสุด = เพิ่มล่าสุด) และคืนค่าเป็น Tuple (key, value)

Collection of Collections 🪆

โครงสร้างข้อมูลซ้อนกัน — nested collection

Collection of Collections

ข้อมูลที่ซับซ้อน สามารถจัดเก็บในรูปแบบ Collection ซ้อน Collection ได้:

  • List of List[[...], [...], ...]
  • List of Dict[{...}, {...}, ...]
  • Dict of List{"key": [...], ...}
  • และรูปแบบอื่น ๆ อีกมากมาย

List of List

items = [
    ["John","male",180.5,80],
    ["Jane","female",176,60.5],
    ["Steve","male",187.5,82]
]

โจทย์ #35

เข้าถึงข้อมูลใน List of List แล้วคำนวณค่าเฉลี่ยส่วนสูง \(\frac{180.5+176+187.5}{3}\)

items = [["John","male",180.5,80], ["Jane","female",176,60.5], ["Steve","male",187.5,82]]
print(items[0])
print(items[1])
print(items[2])

average_height = (items[0][2] + items[1][2] + items[2][2]) / len(items)
print(f'Average height: {average_height}')
['John', 'male', 180.5, 80]
['Jane', 'female', 176, 60.5]
['Steve', 'male', 187.5, 82]
Average height: 181.33333333333334

ตัวอย่าง: เพิ่ม/ลบใน List of List

ใช้ .append() / .pop() เหมือน List ปกติ (มอง List ข้างใน 1 ตัวเป็น 1 object)

items = [["John","male",180.5,80], 
         ["Jane","female",176,60.5], 
         ["Steve","male",187.5,82]]
items.append(["Lisa","female",168,48])  # บรรทัดนี้ทำอะไร?
data = items.pop(0)   # บรรทัดนี้ทำอะไร?
print(f"data = {data}")
print(f"items = {items}")
data = ['John', 'male', 180.5, 80]
items = [['Jane', 'female', 176, 60.5], ['Steve', 'male', 187.5, 82], ['Lisa', 'female', 168, 48]]

List of Dict

items2 = [
    { 
        "name": "John",
        "gender": "male", 
        "height": 180.5,
        "weight": 80
    },
    {
        "name": "Jane",
        "gender": "female",
        "height": 176,
        "weight": 60.5
    },
    {
        "name": "Steve",
        "gender": "male",
        "height": 187.5,
        "weight": 82
    }
]

โจทย์ #36

เข้าถึงข้อมูลใน List of Dict แล้วคำนวณค่าเฉลี่ยส่วนสูง \(\frac{180.5+176+187.5}{3}\)

items2 = [
    {"name":"John","gender":"male","height":180.5,"weight":80},
    {"name":"Jane","gender":"female","height":176,"weight":60.5},
    {"name":"Steve","gender":"male","height":187.5,"weight":82}
]
print(items2[0])
print(items2[1])
print(items2[2])

average_height = (items2[0]["height"] + items2[1]["height"] + items2[2]["height"]) / len(items2)
print(f'Average height: {average_height}')
{'name': 'John', 'gender': 'male', 'height': 180.5, 'weight': 80}
{'name': 'Jane', 'gender': 'female', 'height': 176, 'weight': 60.5}
{'name': 'Steve', 'gender': 'male', 'height': 187.5, 'weight': 82}
Average height: 181.33333333333334

ตัวอย่าง: เพิ่ม/ลบใน List of Dict

วิธีเดียวกับ List of List — ต่างที่แต่ละ item เป็น Dict

items2 = [
    {"name":"John","gender":"male","height":180.5,"weight":80},
    {"name":"Jane","gender":"female","height":176,"weight":60.5},
]
items2.append({'name': 'Lisa', 'gender': 'female', 'height': 168, 'weight': 48})
data = items2.pop(0)
print(data)
print(items2)
{'name': 'John', 'gender': 'male', 'height': 180.5, 'weight': 80}
[{'name': 'Jane', 'gender': 'female', 'height': 176, 'weight': 60.5}, {'name': 'Lisa', 'gender': 'female', 'height': 168, 'weight': 48}]

Dict of List

items3 = {
    "John":  ["male",180.5,80],
    "Jane":  ["female",176,60.5],
    "Steve": ["male",187.5,82]
}

ตัวอย่าง: เข้าถึง Dict of List

เข้าถึงข้อมูลใน Dict of List แล้วคำนวณค่าเฉลี่ยส่วนสูง \(\frac{180.5+176+187.5}{3}\)

แนวคิด: เข้าถึงด้วย key แล้วตามด้วย index ของ List ข้างใน → items3["John"][1]

items3 = {
    "John":  ["male",180.5,80],
    "Jane":  ["female",176,60.5],
    "Steve": ["male",187.5,82]
}
average_height = (items3["John"][1] + items3["Jane"][1] + items3["Steve"][1]) / len(items3)
print(f'Average height: {average_height}')
Average height: 181.33333333333334

ตัวอย่าง: เพิ่ม/ลบใน Dict of List

  • เพิ่มด้วยการกำหนด key ใหม่
  • ลบด้วย .pop(key)
items3 = {
    "John":  ["male",180.5,80],
    "Jane":  ["female",176,60.5],
}
items3["Lisa"] = ["female",168,48]   # เพิ่ม key='Lisa', value=["female",168,48]
data = items3.pop("John")            # เอา key='Jonh' ออกพร้อม assign ค่าให้ data
print(data)
print(items3)
['male', 180.5, 80]
{'Jane': ['female', 176, 60.5], 'Lisa': ['female', 168, 48]}

Other Possibility — Nested Collection

เราสามารถประยุกต์ใช้ collection ในการจัดเก็บข้อมูลที่ซับซ้อน (มีความลึกได้หลายชั้น)

ตัวอย่าง — จัดเก็บข้อมูลนักเรียนด้วย Dict ที่มีข้อมูลหลายชนิดซ้อนกัน

student1 = {
    'id': 650610123,                                      # integer
    'name': 'Peter Hamilton',                             # string
    'gpax': 3.45,                                         # float
    'isMale': True,                                       # boolean
    'grades': {'259201':'A','259104':'B+','259106':'B+'},  # Dict
    'hobbies': ['gaming','running','K-drama'],            # List
}

โจทย์ #37

นำข้อมูลนักเรียนมาเก็บรวมกันใน list แล้วคำนวณ GPAX เฉลี่ย

students = [student1, student2]
average_gpa = (students[0]['gpax'] + students[1]['gpax']) / len(students)
print(f'average GPA: {average_gpa}')
average GPA: 3.525

โจทย์ #38

เพิ่ม hobby ให้กับ student2 และดูเกรดวิชา 259201 ของ student1

students = [student1, student2]

students[1]['hobbies'].append('novel')
print(students[1])   

print(students[0]['grades'][259201])
{'id': 650610203, 'name': 'Thanya Taylor', 'gpax': 3.6, 'isMale': False, 'grades': {'259201': 'B+', '259104': 'A', '259106': 'B'}, 'hobbies': ['novel']}
A

Summary

สรุป Module 4b

Tuple (...)

  • Immutable, ordered
  • ใช้ len(), slice ได้เหมือน List
  • แปลงด้วย list() / tuple()

Set {...}

  • Unique, unordered, ไม่มี index
  • .add(), .update()
  • .remove(), .discard(), .clear()
  • union() / |, intersection() / &, -
  • .issubset()

Dictionary {key: value}

  • อ้างอิงด้วย key แทน index
  • .keys(), .values(), .items()
  • .pop(), .popitem(), .clear()

Collection of Collections

  • List of List, List of Dict, Dict of List
  • Nested collection สำหรับข้อมูลซับซ้อน