Values ใน Python dictionary ไม่สามารถ slice เหมือน list ได้ เพราะ dictionaries มี custom key values ไม่ได้ indexed จากศูนย์ ถ้าพยายาม slice dictionary เหมือน list จะเจอ error TypeError: unhashable type: 'slice'
คู่มือนี้อธิบาย error นี้หมายถึงอะไร และทำไมเห็นในโค้ด พร้อมตัวอย่าง ช่วยแก้ได้
TypeError: unhashable type: 'slice'
Slice คือ subset ของ sequence เช่น string, list, tuple ชื่อบ่งบอก purpose: คือ "a slice" ของ sequence
โปรแกรมตัวอย่าง:
news_sites = ["New York Times", "Washington Post", "CNN"] print(news_sites[:2])
โค้ดดึง 2 ค่าแรกใน "news_sites" list พิมพ์คอนโซล คืนค่า: ['New York Times', 'Washington Post']
นี่คือตัวอย่าง slicing ระบุ colon และ index value บอก Python ว่าดึง objects ไหน
Dictionaries ไม่สามารถ slice เหมือน list ได้ Dictionaries ไม่มี index numbers ดังนั้น syntax นี้ไม่ apply
ตัวอย่าง Error (TypeError: unhashable type: 'slice')
สร้างโปรแกรมแสดงข้อมูลคีย์บอร์ดขายที่ร้าน hardware เริ่มกำหนด dictionary ข้อมูลคีย์บอร์ด:
keyboard = {
"name": "Huntsman Mini",
"brand": "Razer",
"price": 119.99,
"switch_type": "Razer Switches",
}
โปรแกรมเก็บ: name, price, brand, switch type ของคีย์บอร์ด ต้องการแสดงแค่: name, brand, price
Slice ดึง 3 items แรกใน dictionary items นี้คือ name, brand, price:
show_to_customer = keyboard[:3]
โค้ดดึง 3 items แรกใน dictionary ต่อไป for loop วนลิสต์นี้ พิมพ์แต่ละ item คอนโซล:
for s in show_to_customer:
print(s[1])
ใช้ indexing ดึง value จากแต่ละ record ใน "show_to_customer" พิมพ์ค่าด้วย print() statement รันโค้ด:
Traceback (most recent call last): File "main.py", line 8, inshow_to_customer = keyboard[:3] TypeError: unhashable type: 'slice'
โค้ด error
วิธีแก้ (The Solution)
ไม่เหมือน lists dictionaries ไม่สามารถ slice ได้ ไม่สามารถดึง items ใน dictionary ด้วย slicing เพราะไม่มี index numbers ข้อมูลเก็บเป็น key-value pairs เพราะ dictionaries ไม่ slice ได้ for loop ก่อนหน้าจึงไม่เหมาะสม
ต้องระบุโดยตรงว่าต้องการเข้าถึงค่าไหนจาก dictionary ใช้ key names ที่เหมาะสมใน dictionary
แก้โค้ด: เข้าถึงค่าที่ต้องการแสดงคอนโซลทีละตัว:
keyboard = {
"name": "Huntsman Mini",
"brand": "Razer",
"price": 119.99,
"switch_type": "Razer Switches",
}
print("Name: " + keyboard["name"])
print("Brand: " + keyboard["brand"])
print("Price: $" + str(keyboard["price"]))
แต่ละ print() statement อ้างอิงค่าต่างกันใน dictionary print แรก: label "Name: " ตามด้วย value "name" ใน dictionary print ที่ 2 และ 3: value "brand" และ "price" ตามลำดับ
แปลง "price" เป็น string ด้วย str() method เพื่อ concatenate กับ "Price: $" label ด้วย concatenation operator (+)
รันโปรแกรมใหม่:
Name: Huntsman Mini Brand: Razer Price: $119.99
โค้ดพิมพ์ 3 ข้อมูลที่ต้องการแสดงคอนโซลสำเร็จ User เห็น name, brand, price ของคีย์บอร์ด
สรุป
Error TypeError: unhashable type: 'slice' เกิดเมื่อพยายามเข้าถึง items จาก dictionary ด้วย slicing syntax วิธีแก้: ให้แน่ใจว่าอ้างอิง items ที่ต้องการเข้าถึงจาก dictionary โดยตรง
ตอนนี้คุณมีความรู้แก้ error นี้อย่าง expert แล้ว!