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

คุณสมบัติของ Dictionary Keys ใน Python

ค่าของ Dictionary (Dictionary values) ไม่มีข้อจำกัด สามารถเป็นอ็อบเจ็กต์ Python แบบสุ่มได้ ไม่ว่าจะเป็น standard objects หรือ user-defined objects อย่างไรก็ตาม สิ่งเดียวกันไม่จริงสำหรับ keys

มีสองจุดสำคัญที่ต้องจำเกี่ยวกับ dictionary keys:

  • ไม่สามารถมี entry มากกว่าหนึ่งต่อ key ได้ หมายถึงไม่มี duplicate key allowed เมื่อพบ duplicate keys ระหว่างการกำหนดค่า การกำหนดค่าครั้งสุดท้ายจะชนะ

ตัวอย่าง

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

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

ผลลัพธ์ (Output)

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

dict['Name']: Manni
  • Keys ต้องเป็น immutable หมายถึงคุณสามารถใช้ strings, numbers หรือ tuples เป็น dictionary keys ได้ แต่องค์อย่าง [ 'key' ] ไม่ได้

ตัวอย่าง

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

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

ผลลัพธ์ (Output)

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

Traceback (most recent call last):
  File "test.py", line 3, in 
    dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'