ข้ามไปยังเนื้อหาหลัก
Editor

ดิกชันนารีใน Python: คู่มือฉบับสมบูรณ์พร้อมตัวอย่างจริง

เริ่มต้น30 นาที8 แบบฝึกหัด110 XP

บทเรียนนี้แปลจากต้นฉบับภาษาอังกฤษRead in EnglishLeer en españolЧитать на русскомLer em portuguêsแจ้งข้อผิดพลาดในการแปล

0/8 แบบฝึกหัด

เปิดแอปรายชื่อผู้ติดต่อในโทรศัพท์ของคุณ คุณค้นหาคนจาก ชื่อ แล้วได้ เบอร์โทรศัพท์ ของเขา คุณไม่ได้ค้นจากตำแหน่ง ไม่ได้บอกว่า "ขอรายชื่อลำดับที่ 47" คุณค้นจากชื่อ

ดิกชันนารี (dictionary) ใน Python ทำงานแบบเดียวกันเลย แทนที่จะเก็บข้อมูลตามตำแหน่ง (แบบลิสต์) ดิกชันนารีเก็บข้อมูลเป็น คู่คีย์-ค่า (key-value pair) คีย์คือชื่อที่คุณใช้ค้นหา และค่าคือสิ่งที่คุณได้กลับมา

ดิกชันนารีมีอยู่ทุกที่ในการเขียนโปรแกรมจริง ข้อมูลโปรไฟล์ผู้ใช้ การตั้งค่าโปรแกรม ข้อมูล JSON จาก API ตัวนับคำ ล้วนใช้ดิกชันนารีทั้งนั้น ในบทเรียนนี้ คุณจะได้ฝึกการใช้งานดิกชันนารีที่จำเป็นทุกอย่างจนคล่อง

วิธีสร้างดิกชันนารีใน Python

คุณสร้างดิกชันนารีด้วย วงเล็บปีกกา {} โดยใส่คู่คีย์-ค่าที่คั่นคีย์กับค่าด้วยโคลอน และคั่นแต่ละคู่ด้วยเครื่องหมายจุลภาค

สร้างดิกชันนารี
# A simple dictionary
contact = {
'name': 'Alice',
'phone': '555-1234',
'email': 'alice@example.com',
}
print(contact)
ผลลัพธ์
{'name': 'Alice', 'phone': '555-1234', 'email': 'alice@example.com'}

คีย์มักเป็นสตริง แต่จะเป็นค่าใดก็ได้ที่ แฮชได้ (hashable) ซึ่งในทางปฏิบัติคือค่าที่เปลี่ยนแปลงไม่ได้ เช่น ตัวเลข ค่าความจริง หรือทูเพิลของค่าเหล่านี้ ส่วนค่าเป็น อะไรก็ได้ ทั้งสตริง ตัวเลข ลิสต์ หรือแม้แต่ดิกชันนารีอื่น

ค่าหลายชนิดปนกัน และดิกชันนารีว่าง
# Different types of keys and values
student = {
'name': 'Bob',
'age': 16,
'grades': [85, 92, 78],
'active': True,
}
print(student)
# Empty dictionary - two ways
empty1 = {}
empty2 = dict()
print(empty1) # {}
print(empty2) # {}
ผลลัพธ์
{'name': 'Bob', 'age': 16, 'grades': [85, 92, 78], 'active': True}
{}
{}

การเข้าถึงและแก้ไขค่าในดิกชันนารี

ถ้าต้องการดึงค่าจากดิกชันนารี ให้ใส่คีย์ไว้ในวงเล็บเหลี่ยม ถ้าต้องการเปลี่ยนค่า ให้กำหนดค่าใหม่ให้คีย์นั้น ถ้าต้องการเพิ่มคู่ใหม่ ก็แค่กำหนดค่าให้คีย์ที่ยังไม่มีอยู่

เข้าถึง แก้ไข และเพิ่มค่า
person = {'name': 'Alice', 'age': 25, 'city': 'Boston'}
# Access a value by key
print(person['name']) # Alice
print(person['age']) # 25
# Change an existing value
person['age'] = 26
print(person['age']) # 26
# Add a new key-value pair
person['job'] = 'Engineer'
print(person)
ผลลัพธ์
Alice
25
26
{'name': 'Alice', 'age': 26, 'city': 'Boston', 'job': 'Engineer'}
เข้าถึงอย่างปลอดภัยด้วย get()
person = {'name': 'Alice', 'age': 25}
# This would crash:
# print(person['salary']) # KeyError!
# Safe way: use .get() with a default value
print(person.get('salary', 'Not specified')) # Not specified
print(person.get('name', 'Unknown')) # Alice
ผลลัพธ์
Not specified
Alice
ไม่ปลอดภัย: วงเล็บเหลี่ยมหยุดทำงานเมื่อไม่มีคีย์
data = {'x': 10}
# Crashes with KeyError:
value = data['y']
ปลอดภัย: get() คืนค่าเริ่มต้น
data = {'x': 10}
# Returns 0 if 'y' is missing:
value = data.get('y', 0)

เมธอดที่จำเป็นของดิกชันนารี

ดิกชันนารีมีเมธอดในตัวหลายตัวที่ช่วยให้ทำงานได้ง่าย นี่คือเมธอดที่คุณจะใช้บ่อยที่สุด

keys(), values() และ items()
fruit_prices = {'apple': 1.50, 'banana': 0.75, 'cherry': 3.00}
# keys() - get all keys
print(list(fruit_prices.keys())) # ['apple', 'banana', 'cherry']
# values() - get all values
print(list(fruit_prices.values())) # [1.5, 0.75, 3.0]
# items() - get all key-value pairs as tuples
print(list(fruit_prices.items())) # [('apple', 1.5), ('banana', 0.75), ('cherry', 3.0)]
ผลลัพธ์
['apple', 'banana', 'cherry']
[1.5, 0.75, 3.0]
[('apple', 1.5), ('banana', 0.75), ('cherry', 3.0)]
pop() และ update()
inventory = {'apples': 5, 'bananas': 3, 'oranges': 8}
# pop() - remove a key and return its value
removed = inventory.pop('bananas')
print(removed) # 3
print(inventory) # {'apples': 5, 'oranges': 8}
# update() - merge another dictionary into this one
inventory.update({'grapes': 12, 'apples': 10})
print(inventory) # {'apples': 10, 'oranges': 8, 'grapes': 12}
ผลลัพธ์
3
{'apples': 5, 'oranges': 8}
{'apples': 10, 'oranges': 8, 'grapes': 12}

สังเกตว่า update() ทั้งเพิ่มคีย์ใหม่และเขียนทับคีย์ที่มีอยู่แล้ว ในตัวอย่างด้านบน 'apples' เปลี่ยนจาก 5 เป็น 10 และ 'grapes' ถูกเพิ่มเข้ามาเป็นคีย์ใหม่

วนลูปผ่านดิกชันนารี

คุณวนลูปผ่านคีย์ ค่า หรือทั้งสองอย่างของดิกชันนารีได้ วิธีที่ใช้บ่อยที่สุดคือวนลูปผ่าน items() เพื่อให้ได้ทั้งคีย์และค่าในคราวเดียว

สามวิธีวนลูปผ่านดิกชันนารี
scores = {'Alice': 95, 'Bob': 87, 'Charlie': 72}
# Loop through keys (default)
for name in scores:
print(name)
print('---')
# Loop through values
for score in scores.values():
print(score)
print('---')
# Loop through both (most useful)
for name, score in scores.items():
print(f'{name}: {score}')
ผลลัพธ์
Alice
Bob
Charlie
---
95
87
72
---
Alice: 95
Bob: 87
Charlie: 72

ตรวจว่ามีคีย์อยู่หรือไม่

ก่อนเข้าถึงคีย์ บ่อยครั้งคุณอยากตรวจก่อนว่ามีคีย์นั้นอยู่ คีย์เวิร์ด in ตรวจหาคีย์ ไม่ใช่ค่า

ใช้ in ตรวจหาคีย์
user = {'name': 'Alice', 'email': 'alice@example.com'}
# Check if a key exists
print('name' in user) # True
print('phone' in user) # False
print('phone' not in user) # True
# Common pattern: check before accessing
if 'email' in user:
print(f'Email: {user["email"]}')
else:
print('No email on file')
ผลลัพธ์
True
False
True
Email: alice@example.com

ดิกชันนารีซ้อนกัน

ค่าในดิกชันนารีเป็นดิกชันนารีอีกตัวได้ เรียกว่า การซ้อน (nesting) ซึ่งช่วยให้แทนข้อมูลที่ซับซ้อนและมีโครงสร้างได้ เช่น ห้องเรียนที่มีนักเรียนหลายคน แต่ละคนมีชุดข้อมูลของตัวเอง

ดิกชันนารีซ้อนกัน
classroom = {
'Alice': {'age': 16, 'grade': 'A'},
'Bob': {'age': 15, 'grade': 'B'},
'Charlie': {'age': 16, 'grade': 'A'},
}
# Access a nested value with chained brackets
print(classroom['Alice']['grade']) # A
print(classroom['Bob']['age']) # 15
# Loop through nested data
for name, info in classroom.items():
print(f'{name} is {info["age"]} and got a {info["grade"]}')
ผลลัพธ์
A
15
Alice is 16 and got a A
Bob is 15 and got a B
Charlie is 16 and got a A

ถ้าต้องการเข้าถึงค่าที่ซ้อนอยู่ ให้ใช้วงเล็บเหลี่ยมต่อกัน: คีย์ด้านนอกก่อน แล้วตามด้วยคีย์ด้านใน คุณซ้อนลึกเท่าไรก็ได้ แต่ถ้าเกินสองหรือสามชั้นจะเริ่มอ่านยาก

ข้อผิดพลาดที่พบบ่อยกับดิกชันนารี

ใช้ทูเพิลเป็นคีย์ของดิกชันนารี
# This works - tuples are immutable
locations = {
(40.71, -74.00): 'New York',
(51.50, -0.12): 'London',
}
print(locations[(40.71, -74.00)]) # New York
# This would crash:
# bad = {[1, 2]: 'nope'} # TypeError: unhashable type: 'list'
ผลลัพธ์
New York
หยุดทำงาน: แก้ไขระหว่างวนลูป
data = {'a': 1, 'b': 2, 'c': 3}
for key in data:
    if data[key] < 2:
        del data[key]  # RuntimeError!
ใช้ได้: วนลูปผ่านสำเนาของคีย์
data = {'a': 1, 'b': 2, 'c': 3}
for key in list(data.keys()):
    if data[key] < 2:
        del data[key]  # Safe!
print(data)  # {'b': 2, 'c': 3}

แบบฝึกหัด

ถึงเวลาฝึกแล้ว แบบฝึกหัดเหล่านี้ไล่ระดับจากการใช้งานดิกชันนารีขั้นพื้นฐาน ไปจนถึงรูปแบบที่ซับซ้อนขึ้น

แบบฝึกหัดที่ 1: สร้างดิกชันนารีและเข้าถึงค่า
เขียนโค้ด

สร้างดิกชันนารีชื่อ pet ที่มีคู่คีย์-ค่าดังนี้:

  • 'name': 'Buddy'
  • 'species': 'dog'
  • 'age': 5
  • จากนั้นแสดงชื่อของสัตว์เลี้ยง

    ผลลัพธ์ที่ควรได้:

    Buddy
    # Create the pet dictionary
    # Print the pet's name
    แบบฝึกหัดที่ 2: เพิ่มและแก้ไขข้อมูลในดิกชันนารี
    เขียนโค้ด

    มีดิกชันนารีที่เก็บข้อมูลหนังสือให้มา ทำตามขั้นตอนต่อไปนี้ตามลำดับ:

    1. เปลี่ยน 'year' เป็น 2024

    2. เพิ่มคีย์ใหม่ 'genre' ที่มีค่า 'fiction'

    3. แสดงดิกชันนารีทั้งหมด

    ผลลัพธ์ที่ควรได้:

    {'title': 'The Great Adventure', 'author': 'Jane Smith', 'year': 2024, 'genre': 'fiction'}
    book = {'title': 'The Great Adventure', 'author': 'Jane Smith', 'year': 2020}
    # Step 1: Change the year to 2024
    # Step 2: Add genre
    # Step 3: Print the dictionary
    แบบฝึกหัดที่ 3: เข้าถึงอย่างปลอดภัยด้วย get()
    เขียนโค้ด

    มีดิกชันนารีโปรไฟล์ผู้ใช้ให้มา ใช้เมธอด .get() เพื่อแสดงเบอร์โทรศัพท์ของผู้ใช้อย่างปลอดภัย ถ้าไม่มีคีย์ 'phone' ให้แสดง 'No phone number'

    ผลลัพธ์ที่ควรได้:

    No phone number
    profile = {'name': 'Alice', 'email': 'alice@mail.com'}
    # Use .get() to safely access the phone key
    แบบฝึกหัดที่ 4: วนลูปผ่านดิกชันนารี
    เขียนโค้ด

    วนลูปผ่านดิกชันนารี แล้วแสดงผลไม้แต่ละชนิดพร้อมราคาในรูปแบบนี้:

    apple: $1.50
    banana: $0.75
    cherry: $3.00

    ราคาต้องแสดงทศนิยมสองตำแหน่งพอดี

    prices = {'apple': 1.5, 'banana': 0.75, 'cherry': 3.0}
    # Loop and print each item
    แบบฝึกหัดที่ 5: ทายผลลัพธ์: คีย์ซ้ำ
    ทายผลลัพธ์

    อ่านโค้ดนี้อย่างละเอียดแล้วทายว่าจะแสดงอะไร จะเกิดอะไรขึ้นเมื่อดิกชันนารีมีคีย์ซ้ำกัน

    พิมพ์ผลลัพธ์ให้ตรงทุกตัวอักษร

    data = {'a': 1, 'b': 2, 'a': 3}
    print(data)
    print(len(data))
    แบบฝึกหัดที่ 6: แก้บั๊ก: ตรวจหาค่า
    แก้บั๊ก

    โค้ดนี้พยายามตรวจว่ามีเกรด 'A' อยู่ในดิกชันนารีหรือไม่ แต่ตรวจผิดที่ แก้ให้แสดงผล:

    Someone got an A!
    grades = {'Alice': 'A', 'Bob': 'B', 'Charlie': 'C'}
    if 'A' in grades:
    print('Someone got an A!')
    else:
    print('No one got an A.')
    แบบฝึกหัดที่ 7: สร้างตัวนับคำ
    เขียนโค้ด

    นับว่าแต่ละคำปรากฏกี่ครั้งในลิสต์ที่ให้มา เก็บจำนวนไว้ในดิกชันนารีชื่อ word_counts แล้วแสดงผล

    ผลลัพธ์ที่ควรได้:

    {'hello': 3, 'world': 2, 'python': 1}
    words = ['hello', 'world', 'hello', 'python', 'hello', 'world']
    # Build a word count dictionary
    # Print the result
    แบบฝึกหัดที่ 8: เข้าถึงข้อมูลในดิกชันนารีซ้อนกัน
    เขียนโค้ด

    มีดิกชันนารีซ้อนกันของนักเรียนให้มา วนลูปผ่านนักเรียนแต่ละคน แล้วแสดงชื่อและคะแนนคณิตศาสตร์ในรูปแบบนี้:

    Alice: 95
    Bob: 82
    Charlie: 91
    students = {
    'Alice': {'math': 95, 'english': 88},
    'Bob': {'math': 82, 'english': 90},
    'Charlie': {'math': 91, 'english': 85},
    }
    # Loop and print each student's math score

    สรุป: สิ่งที่คุณได้เรียนเกี่ยวกับดิกชันนารีใน Python

    เยี่ยมมาก นี่คือสรุปทุกสิ่งที่คุณรู้แล้ว:

    แนวคิดทำอะไรตัวอย่าง
    สร้าง dictเก็บคู่คีย์-ค่าd = {'name': 'Alice'}
    เข้าถึงด้วยคีย์ดึงค่าd['name']
    เข้าถึงอย่างปลอดภัยได้ค่าเริ่มต้นถ้าไม่มีคีย์d.get('x', 0)
    เพิ่ม / แก้ไขกำหนดค่าd['age'] = 25
    keys()คีย์ทั้งหมดd.keys()
    values()ค่าทั้งหมดd.values()
    items()ทูเพิลคีย์-ค่าd.items()
    pop(key)ลบและคืนค่าd.pop('age')
    update()รวม dictd.update(other)
    inตรวจว่ามีคีย์อยู่หรือไม่'name' in d
    การซ้อนdict ภายใน dictd['a']['b']

    ดิกชันนารีเป็นหนึ่งในโครงสร้างข้อมูลที่สำคัญที่สุดใน Python ข้อมูล JSON ผลตอบกลับจาก API ไฟล์ตั้งค่า ตัวนับ ทั้งหมดล้วนอาศัยคู่คีย์-ค่า

    เรียนอะไรต่อ

    ในบทเรียนถัดไป Comprehension ใน Python คุณจะได้เรียนวิธีสร้างลิสต์ ดิกชันนารี และเซต ด้วยโค้ดบรรทัดเดียวที่สวยงาม

    comprehension ช่วยให้คุณแทนที่ลูปหลายบรรทัดด้วยโค้ดบรรทัดเดียวที่กระชับ และเป็นหนึ่งในความสามารถที่ทำให้ Python ดูสะอาดและสื่อความหมายได้ดี

    บทเรียนที่เกี่ยวข้อง

    บทเรียนนี้มีประโยชน์หรือไม่