Skip to content

บทที่ 2.4: ชุดข้อมูลแบบไม่อิงลำดับ (Dictionaries & Sets)

เอกสารนี้อธิบายเกี่ยวกับ Dictionary (โครงสร้างข้อมูลแบบ Key-Value) และ Set (โครงสร้างข้อมูลที่ไม่ซ้ำและไม่อิงลำดับ) การจัดการข้อมูล การใช้ Comprehension และการดำเนินงานทางเซต (Set Operations)


1. Dictionary (พจนานุกรม) - ข้อมูลแบบ Key-Value Pair

Dictionary คือโครงสร้างข้อมูลที่เก็บข้อมูลในลักษณะคู่ Key-Value โดย Key ต้องเป็นค่าที่ไม่ซ้ำกันและเป็นประเภทข้อมูลที่ไม่สามารถเปลี่ยนแปลงได้ (Immutable เช่น str, int, tuple)

1.1 การสร้างและการเข้าถึงข้อมูล

# การสร้าง Dictionary
user = {
    "id": 101,
    "name": "Alex",
    "is_active": True,
    "roles": ["admin", "developer"]
}

# การเข้าถึงข้อมูลด้วย Key
print(user["name"])  # Output: Alex

# การเข้าถึงข้อมูลด้วยวิธีเก็ทแบบปลอดภัย (get method)
# หากไม่พบ Key จะคืนค่า None หรือค่า Default ที่กำหนด แทนการเกิด KeyError
print(user.get("email"))                 # Output: None
print(user.get("email", "not_found"))    # Output: not_found

1.2 การแก้ไข เพิ่ม และลบข้อมูล

student = {"name": "John", "age": 20}

# เพิ่มและแก้ไขข้อมูล
student["age"] = 21           # แก้ไขค่าเดิม
student["grade"] = "A"        # เพิ่ม Key-Value ใหม่

# การลบข้อมูล
del student["grade"]          # ลบตาม Key
removed_val = student.pop("age") # ดึงคู่ออกตาม Key และคืนค่า Value

1.3 การวนอ่านค่าใน Dictionary

person = {"name": "Sarah", "age": 28, "city": "Bangkok"}

# วนอ่านเฉพาะ Key
for key in person.keys():
    print(key)

# วนอ่านเฉพาะ Value
for value in person.values():
    print(value)

# วนอ่าน ทั้ง Key และ Value พร้อมกัน (แนะนำ)
for key, value in person.items():
    print(f"{key}: {value}")

1.4 Dictionary Comprehension

# สร้าง Dict สี่เหลี่ยมผืนผ้าของตัวเลข 1-5
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

2. Set (เซต) - ชุดข้อมูลไม่ซ้ำและไม่อิงลำดับ

Set คือโครงสร้างข้อมูลที่เก็บสมาชิกแบบ ไม่อิงลำดับ (Unordered) และ ไม่มีสมาชิกที่ซ้ำกัน (Unique Values)

2.1 การสร้างและการจัดการ Set

# การสร้าง Set (หากมีค่าซ้ำ ระบบจะตัดออกให้อัตโนมัติ)
numbers = {1, 2, 2, 3, 4, 4, 5}
print(numbers)  # Output: {1, 2, 3, 4, 5}

# ข้อควรระวัง: การสร้าง Set ว่าง ต้องใช้ set() ไม่ใช่ {} (เพราะ {} จะได้ Dict)
empty_set = set()

# การเพิ่มและลบสมาชิก
numbers.add(6)          # เพิ่มสมาชิก
numbers.remove(1)       # ลบสมาชิก (หากไม่พบจะเกิด KeyError)
numbers.discard(99)     # ลบสมาชิก (หากไม่พบจะไม่แจ้ง Error)

2.2 เทคนิคการกำจัดค่าซ้ำใน List ด้วย Set

raw_data = ["apple", "banana", "apple", "orange", "banana"]
unique_data = list(set(raw_data))

print(unique_data)  # Output: ['orange', 'apple', 'banana'] (ลำดับอาจเปลี่ยนแปลง)

2.3 การดำเนินงานทางเซต (Set Operations)

set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

# 1. Union (|): รวมสมาชิกทั้งหมด
print(set_a | set_b)  # Output: {1, 2, 3, 4, 5, 6}

# 2. Intersection (&): เอาเฉพาะสมาชิกที่มีร่วมกัน
print(set_a & set_b)  # Output: {3, 4}

# 3. Difference (-): เอาสมาชิกที่มีใน A แต่ไม่มีใน B
print(set_a - set_b)  # Output: {1, 2}

# 4. Symmetric Difference (^): เอาสมาชิกที่ไม่ซ้ำกันในทั้งสองเซต
print(set_a ^ set_b)  # Output: {1, 2, 5, 6}

3. สรุปเปรียบเทียบโครงสร้างข้อมูลหลักใน Python

โครงสร้าง สัญลักษณ์ การเรียงลำดับ แก้ไขได้ (Mutable) สมาชิกซ้ำได้ ลักษณะการใช้งาน
List [] มีลำดับ ได้ ได้ ชุดข้อมูลทั่วไปที่เปลี่ยนค่าได้
Tuple () มีลำดับ ไม่ได้ ได้ ชุดข้อมูลคงที่ เน้นความเร็ว
Dictionary {k: v} มีลำดับ (3.7+) ได้ ไม่ได้ (เฉพาะ Key) จัดเก็บแบบอ้างอิง Key-Value
Set {} ไม่มีลำดับ ได้ ไม่ได้ จัดเก็บข้อมูลไม่ซ้ำ/คำนวณทางเซต