เรียนรู้การจัดเก็บข้อมูลแบบคู่กุญแจ-ค่า
• เข้าใจแนวคิด Dictionary และการใช้งาน
• สามารถสร้างและเข้าถึงข้อมูลใน Dictionary
• ใช้ Methods ต่างๆ ของ Dictionary ได้
• ประยุกต์ใช้ Dictionary ในสถานการณ์จริง
Dictionary = พจนานุกรมที่เก็บข้อมูลแบบ คู่
• Key (กุญแจ) = คำที่ต้องการค้นหา
• Value (ค่า) = ความหมายหรือข้อมูลของคำนั้น
# สร้าง Dictionary - ใช้เครื่องหมาย { } student = { "name": "สมชาย", "age": 16, "grade": 10, "school": "โรงเรียนมัธยม" }
# แบบที่ 1: สร้างตรงๆ person = { "name": "สมหญิง", "age": 15 } # แบบที่ 2: เริ่มจากเปล่า scores = {} scores["math"] = 85 scores["english"] = 92
# ลืมเครื่องหมาย : (colon) wrong = {"name" "สมชาย"} # ลืมเครื่องหมาย , (comma) wrong = { "name": "สมชาย" "age": 16 } # Key ซ้ำกัน (จะเหลือตัวสุดท้าย) duplicate = { "name": "คนแรก", "name": "คนสุดท้าย" }
• ใช้เครื่องหมาย { }
ครอบ
• แต่ละคู่ใช้ :
คั่นระหว่าง key และ value
• แต่ละคู่ใช้ ,
คั่นกัน
• Key ต้องไม่ซ้ำกัน (ถ้าซ้ำจะเอาค่าสุดท้าย)
ใช้ [key]
หรือ .get(key)
ในการเข้าถึงข้อมูล
# สร้าง Dictionary ข้อมูลนักเรียน student = { "name": "สมชาย", "age": 16, "class": "ม.4/1", "gpa": 3.25 } # วิธีที่ 1: ใช้ [key] print(student["name"]) # สมชาย print(student["age"]) # 16 # วิธีที่ 2: ใช้ .get() (ปลอดภัยกว่า) print(student.get("name")) # สมชาย print(student.get("height")) # None (ไม่มี key นี้)
[key]
จะ Error ถ้า key ไม่มี, แต่ .get(key)
จะให้ None
สามารถเพิ่ม, แก้ไข, หรือลบข้อมูลได้ตลอดเวลา
# สร้าง Dictionary คะแนนสอบ scores = { "math": 80, "english": 75 } # แก้ไขข้อมูลที่มีอยู่ scores["math"] = 85 print(scores) # {'math': 85, 'english': 75} # เพิ่มข้อมูลใหม่ scores["science"] = 90 scores["thai"] = 88 # ลบข้อมูล del scores["english"] print(scores) # {'math': 85, 'science': 90, 'thai': 88}
สร้าง Dictionary เก็บข้อมูลเพื่อนในห้อง แล้วลองเพิ่มเพื่อนใหม่
ได้ Key ทั้งหมดใน Dictionary
student.keys() # dict_keys(['name', 'age'])
ได้ Value ทั้งหมดใน Dictionary
student.values() # dict_values(['สมชาย', 16])
ได้คู่ (key, value) ทั้งหมด
student.items() # dict_items([('name', 'สมชาย'), ('age', 16)])
ลบ key และคืน value ของมัน
age = student.pop("age") # age = 16, ลบ age ออกจาก dict
สามารถวนลูปดู Key, Value, หรือทั้งคู่ได้
# ข้อมูลคะแนนสอบ scores = { "คณิต": 85, "อังกฤษ": 92, "วิทยาศาสตร์": 78 } # แบบที่ 1: วนลูป Key for subject in scores: print(f"วิชา: {subject}") # แบบที่ 2: วนลูป Value for score in scores.values(): print(f"คะแนน: {score}") # แบบที่ 3: วนลูปทั้งคู่ for subject, score in scores.items(): print(f"{subject}: {score} คะแนน")
สามารถใส่ Dictionary ใน Dictionary ได้ - เหมาะสำหรับข้อมูลที่มีหลายระดับ
# ข้อมูลนักเรียนหลายคน classroom = { "student1": { "name": "สมชาย", "age": 16, "scores": {"math": 85, "english": 90} }, "student2": { "name": "สมหญิง", "age": 15, "scores": {"math": 92, "english": 88} } } # เข้าถึงข้อมูลซ้อน print(classroom["student1"]["name"]) # สมชาย print(classroom["student1"]["scores"]["math"]) # 85
• ค้นหาข้อมูลเร็ว
• ใช้ชื่อ (key) ที่เข้าใจง่าย
• เหมาะสำหรับข้อมูลที่มีป้ายชื่อ
• ไม่มีลำดับ (Python 3.7+ มีลำดับ)
• ใช้หน่วยความจำมากกว่า
• มีลำดับชัดเจน
• ใช้หน่วยความจำน้อย
• เหมาะสำหรับข้อมูลซ้ำได้
• ค้นหาข้อมูลช้า
• ใช้ตำแหน่ง (index) เข้าถึง
Dictionary: ข้อมูลมีป้ายชื่อ เช่น ข้อมูลนักเรียน, การตั้งค่า, คะแนนสอบ
List: ข้อมูลเป็นลำดับ เช่น รายชื่อ, คะแนนตามเวลา, ขั้นตอนการทำงาน
ใช้ Dictionary เก็บข้อมูลตัวละครในเกม
# ข้อมูลตัวละครเกม character = { "name": "นักผจญภัย", "level": 5, "hp": 100, "mp": 50, "inventory": ["ดาบ", "โล่", "ยาแก้พิษ"], "stats": { "strength": 15, "defense": 12, "speed": 10 } } # แสดงข้อมูลตัวละคร print(f"ชื่อ: {character['name']}") print(f"เลเวล: {character['level']}") print(f"HP: {character['hp']}/{character['hp']}") # เพิ่มของในกระเป๋า character["inventory"].append("เหรียญทอง")
# Key ไม่มีอยู่ student = {"name": "สมชาย"} print(student["age"]) # KeyError! # ลืมเครื่องหมาย "" scores = {math: 85} # NameError! # ใช้ list แทน dict data = ["name", "สมชาย"] print(data["name"]) # TypeError!
# ใช้ .get() หรือตรวจสอบก่อน student = {"name": "สมชาย"} age = student.get("age", 0) # 0 (default) # Key เป็น string scores = {"math": 85} # ถูกต้อง # ใช้ dict data = {"name": "สมชาย"} print(data["name"]) # สมชาย
.get(key, default_value)
เพื่อป้องกัน KeyError
สร้าง dict เก็บชื่อเพื่อน 3 คนและเบอร์โทรศัพท์ เช่น {"Alice": "0812345678", ...}
# ตัวอย่างโค้ด
friends = {
"Alice": "0812345678",
"Bob": "0898765432",
"Charlie": "0876543210"
}
print(friends)
ให้รับชื่่อเพื่อนจากผู้ใช้ แล้วแสดงเบอร์โทรศัพท์ ถ้าไม่พบให้แสดง "ไม่พบ"
# ตัวอย่างโค้ด
name = input("Enter friend's name: ")
if name in friends:
print(friends[name])
else:
print("ไม่พบ")
เขียนโค้ดแสดงชื่อเพื่อนและเบอร์โทรศัพท์ทุกคน ใน 1 บรรทัด
# ตัวอย่างโค้ด
for name, phone in friends.items():
print(f"{name}: {phone}")
รับชื่อและเบอร์จากผู้ใช้ แล้วเพิ่มเข้า dict ถ้าชื่อซ้ำให้แสดง "มีชื่ออยู่แล้ว"
# ตัวอย่างโค้ด
new_name = input("Enter new name: ")
new_phone = input("Enter new phone: ")
if new_name in friends:
print("มีชื่ออยู่แล้ว")
else:
friends[new_name] = new_phone
print("เพิ่มเรียบร้อย!")