Dictionary คือ ชุดข้อมูลแบบ unordered สามารถเปลี่ยนแปลงแก้ไข และสามารถอ้างถึง (indexed) ได้

Dictionary ใน Python จะเป็นคู่ key และ value เขียนโดยใช้วงเล็บแบบ curly brackets ล้อมรอบ

การเข้าถึง items ใน Dictionary

สามารถเข้าถึง items ได้โดยการอ้างด้วยชื่อ key ที่อยู่ในวงเล็บ

student = {'name':'James', 'age':26, 'Nationality':'Thai'}

x = student['name']
print(x)

Output:
James

นอกจากนั้นยังสามารถใช้ method get() ที่ให้ผลลัพธ์แบบเดียวกัน

x = student.get('name')
print(x)

Output:
James

การเปลี่ยนค่า value ใน dictionary

เปลี่ยนค่า value โดยการอ้างชื่อ key ที่ต้องการเปลี่ยนค่านั้น

student['name'] = 'Ashley'
x = student.get('name')
print(x)

Output:
Ashley

การแสดงค่า key หรือ value

ใช้ for…loop เพื่อแสดง key ทั้งหมด

student = {'name':'James', 'age':26, 'Nationality':'Thai'}

for x in student:
  print(x)

Output:
name
age
Nationality

ใช้ for…loop แสดงค่า value ทั้งหมด

for x in student:
  print(student[x])

Output:
26
James
Thai

ใช้ key() method แสดงชื่อ key ทั้งหมด

for x in student.keys():
  print(x)

Output:
Nationality
age
name

ใช้ value() method แสดงค่า value ทั้งหมด

for x in student.values():
  print(x)

Output:
26
Thai
James

แสดงค่า key และ value ด้วยกันเป็นคู่โดยใช้ items() method

for x,y in student.items():
  print(x,y)

Output:
age 26
name James
Nationality Thai

การใช้ items() method บน dictionary (ไม่ใช้ใน for…loop) จะแสดงค่าคู่ key-value ในรูปแบบของ tuple ที่อยู่ใน list

#tuple จะคลุมด้วยเครื่องหมายวงเล็บ parentheses
#list คลุมด้วยเครื่องหมายวงเล็บ square brackets

x = student.items()
print(x)

Output:
dict_items([('name','James'),('Nationality','Thai'),('age',26)])

การตรวจสอบ key-value ใน dictionary

ใช้ if…else statement

if 'name' in student:
  print('There is a key name in dictionary')
else:
  print('There is no key name in dictionary')

ตรวจสอบว่ามีคู่ key และ value กี่คู่ใน Dictionary โดยใช้ len() function

print(len(student))

Output:
3

เพิ่ม และ ลบ items ใน dictionary

สร้าง key ใหม่และ assign ค่า value

student['height'] = 170

ลบ items ออกจาก dictionary โดยใช้ pop() method

student.pop('Nationality')

ใช้ popitem() method ลบ item ตัวล่าสุดที่เพิ่มเข้าไป (version ก่อนหน้า 3.7 จะลบแบบสุ่ม)

student.popitem()

ใช้ keyword del เพื่อลบ item ที่มีชื่อที่ต้องการ

del student['age']

สามารถใช้ del เพื่อลบ dictionary ออกทั้งหมดได้ด้วย เมื่อลบแล้ว จะไม่มี dictionary นี้อีก

del student

ใช้ clear() method เพื่อลบชุดข้อมูลทั้งหมดใน dictionary จะเหลือ dictionary ว่าง

student.clear()

ใช้ update() method เพื่อเพิ่ม key และ value

student = {‘name’: ‘Anna’, ‘age’: 23}

student.update({‘surname’: ‘Alison’})
print(student)

Output:
{‘name’: ‘Anna’, ‘surname’: ‘Alison’, ‘age’: 23}

คัดลอก Dictionary

ไม่สามารถคัดลอกโดยใช้เครื่องหมายเท่ากับได้ เช่น

student1 = student2

เพราะการใช้เครื่องหมายเท่ากับแบบตัวอย่างด้านบนนี้จะเป็นการอ้างถึงจาก dictionary หนึ่งไปยัง dictionary อีกอันหนึ่งเท่านั้น หากมีเราทำการเปลี่ยนแปลงแก้ไขข้อมูลใน student1 ข้อมูลใน student2 จะถูกแก้ไขไปด้วย

การคัดลอก dictionary ใช้ built-in dictionary method copy()

newStudent = student.copy()

ใช้ built-in function dict()

newStudent = dict(student)

Nested Dictionary

dictionary ที่มี dictionary อื่นอยู่ข้างในเรียกว่า nested dictionary

myStudents = {'student1': {'name': 'Lily', 'age': 26}, 'student2': {'name': 'James', 'age': 28}, 'student3': {'name': 'Anna', 'age': 23}}

หรือ nest dictionary ที่มีอยู่แล้ว

student1 = {'name': 'Lily', 'age': 26}
student2 = {'name': 'James', 'age': 28}
student3 = {'name': 'Anna', 'age': 23}

myStudents = {'student1': student1, 'student2': student2, 'student3': student3}

Dict() Constructor

สร้าง dictionary ใหม่โดยการใช้ dict() constructor

student = dict(name = 'Anna', age = 23)

#key จะไม่อยู่ใน quotation mark
#ใช้เครื่องหมายเท่ากับ (equal signs) แทนการใช้ colon ในการ assign value
#ใช้วงเล็บ parentheses

fromkeys() method

เป็นการสร้าง dictionary ที่มี key หลาย key ตามที่กำหนด โดยแต่ละ key จะมี value เดียวกัน

students = (‘student1’, ‘student2’, ‘student3’)
age = 25

myStudents = dict.fromkeys(students,age)
print(myStudents)

Output:
{‘student1’: 25, 'student2': 25, ‘student3’: 25}

setdefault() method

เป็นการ search หา key ใน dictionary หากมี key ดังกล่าวใน dictionary และมีค่า value อยู่แล้ว เมื่อรันโปรแกรมก็จะรีเทิร์นค่า value นั้น
หากไม่มี key ดังกล่าวใน dictionary เมื่อ รันโปรแกรม จะรีเทิร์นค่า default ที่ตั้งไว้

student = {'name': 'Anna','age': 23}

x = student.setdefault('age', None)
print(x)

y = student.setdefault('class','Math')
print(y)

สรุป Dictionary Method:

Python มี built-in method ที่สามารถใช้กับ Dictionary ได้ดังนี้

  • clear() -> ลบ items/elements ทั้งหมดออกจาก dictionary
  • copy() -> คัดลอก dictionary
  • fromkeys() -> สร้าง dictionary หลาย keys ที่มี value เดียวกัน
  • get() -> แสดง value ของ key ที่ต้องการ
  • items() -> แสดงคู่ key-value ในรูปของ tuple ที่อยู่ใน list
  • keys() -> แสดง key ทั้งหมด
  • values() -> แสดง value ทั้งหมด
  • pop() -> ลบ element โดยระบุชื่อ key ของ element ที่ต้องการลบ
  • popitem() -> ลบ element อันล่าสุดที่เพิ่มเข้ามา
  • setdefault() -> แสดงค่า value ของ key ที่ระบุ หากไม่พบ key ดังกล่าว เพิ่ม key ดังกล่าวลง dictionary และ assign ค่า value เป็นค่า default ที่ตั้ง
  • update() -> เพิ่มคู่ key-value ใหม่ลง dictionary