Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การเข้าถึงค่า Dictionary (Accessing Values of Dictionary) ใน Python

เพื่อเข้าถึงสมาชิก dictionary คุณสามารถใช้ square brackets ที่คุ้นเคยพร้อมกับ key เพื่อรับค่าของมัน

ตัวอย่าง

ตัวอย่างง่ายๆ ดังนี้:

#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

ผลลัพธ์ (Output)

เมื่อรันโค้ดข้างต้น จะได้ผลลัพธ์ดังนี้:

dict['Name']: Zara
dict['Age']: 7

หากเราพยายามเข้าถึงข้อมูลด้วย key ที่ไม่ใช่ส่วนหนึ่งของ dictionary เราจะได้ error ดังนี้:

ตัวอย่าง

#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']

ผลลัพธ์ (Output)

เมื่อรันโค้ดข้างต้น จะได้ผลลัพธ์ดังนี้:

dict['Alice']: Traceback (most recent call last):
  File "test.py", line 4, in 
    print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'