Python Dictionary

   อัปเดตล่าสุด April 20, 2024

Dictionary คือ โครงสร้างข้อมูลในภาษา Python ที่ใช้ในการจัดเก็บข้อมูลในรูปแบบคู่ key-value โดยที่ key จะเป็นตัวระบุเฉพาะของข้อมูล และ value จะเป็นค่าที่สอดคล้องกับ key นั้น ๆ ตัวอย่างเช่น

student = {
"name": "John Doe",
"age": 18,
"grade": 12
}

ในตัวอย่างนี้ student คือ dictionary ที่ประกอบด้วย key-value pairs สามคู่ โดย key ได้แก่ name,  age, และ grade และ value ที่สอดคล้องกันคือ  John Doe, 18, และ 12 ตามลำดับ


โครงสร้างของ Dictionary

Dictionary ใน Python ถูกกำหนดโดยใช้วงเล็บปีกกา `{}` และมีคู่ key-value ที่คั่นด้วยเครื่องหมายจุลภาค (`,`) โดยที่ key และ value จะถูกแยกด้วยเครื่องหมายโคลอน (`:`) ดังตัวอย่าง

my_dict = {
"key1": value1,
"key2": value2,
"key3": value3
}

โดย key ใน dictionary จะต้องเป็น immutable object เช่น string, number, หรือ tuple ในขณะที่ value สามารถเป็นข้อมูลชนิดใดก็ได้ รวมถึง dictionary อื่น ๆ ด้วย


การใช้งาน Dictionary 

1. การเข้าถึงค่าใน dictionary สามารถทำได้โดยใช้ key ในวงเล็บสี่เหลี่ยม [ ] ดังนี้

student = {
"name": "John Doe",
"age": 18,
"grade": 12
}

print(student["name"]) # Output: John Doe
print(student["age"]) # Output: 18


2. การเพิ่มหรือแก้ไขค่าใน dictionary สามารถทำได้โดยใช้ key ในวงเล็บสี่เหลี่ยม [] และกำหนดค่าให้กับ key นั้น ๆ

student = {
"name": "John Doe",
"age": 18,
"grade": 12
}

student["age"] = 19
student["school"] = "ABC School"

print(student)
# Output: {'name': 'John Doe', 'age': 19, 'grade': 12, 'school': 'ABC School'}


3. การลบค่าใน dictionary สามารถทำได้โดยใช้คำสั่ง del ตามด้วย key ที่ต้องการลบ

student = {
"name": "John Doe",
"age": 18,
"grade": 12
}

del student["grade"]

print(student) # Output: {'name': 'John Doe', 'age': 18}


4. การวนลูปเพื่อเข้าถึงค่าใน dictionary สามารถทำได้โดยใช้คำสั่ง `for` ร่วมกับเมธอด `items()`, keys(), หรือ values()

student = {
"name": "John Doe",
"age": 18,
"grade": 12
}

for key, value in student.items():
print(key + ": " + str(value))

# Output:
# name: John Doe
# age: 18
# grade: 12


จากด้านบนเป็นเพียงส่วนหนึ่งของการใช้งาน dictionary ในภาษา Python โดยยังมีเมธอดและเทคนิคอื่น ๆ อีกมากมายที่สามารถนำไปประยุกต์ใช้ในการจัดการกับข้อมูลในรูปแบบ key-value ได้อย่างมีประสิทธิภาพ ซึ่งสามารถศึกษาเพิ่มเติมเชิงลึกได้เลยครับ



คอร์สเรียนแนะนำ