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

แปลง Tuple เป็น Dictionary แบบ Adjacent Pair ใน Python

บทนำ

การแปลง tuple เป็น dictionary โดยจับคู่ element ติดกันเป็น key-value pairs (index 0-1, 2-3, 4-5...) สามารถทำได้ด้วย dictionary comprehension และ slicing

ตัวอย่างโค้ด

my_tuple = (7, 8, 3, 4, 3, 2)
print("Tuple:", my_tuple)

# สร้าง dict จากคู่ติดกัน: (0,1), (2,3), (4,5)...
result = {my_tuple[i]: my_tuple[i+1] for i in range(0, len(my_tuple), 2)}

print("Dictionary:", result)

ผลลัพธ์

Tuple: (7, 8, 3, 4, 3, 2)
Dictionary: {7: 8, 3: 2}

คำอธิบาย

  • range(0, len(my_tuple), 2) สร้าง index 0, 2, 4, ... (กระโดดทีละ 2)
  • my_tuple[i]: my_tuple[i+1] จับคู่ element i เป็น key, i+1 เป็น value
  • Key 3 ซ้ำ 2 ครั้ง (index 2 และ 4) ค่าสุดท้าย (2) จะทับค่าแรก (4)

วิธีอื่น: ใช้ zip กับ slicing

keys = my_tuple[::2]   # index 0, 2, 4...
values = my_tuple[1::2] # index 1, 3, 5...
result = dict(zip(keys, values))
print(result)  # {7: 8, 3: 2}

กรณี Tuple ความยาวคี่

t = (1, 2, 3)  # ความยาว 3
# zip จะหยุดที่สั้นกว่า → ได้แค่ {1: 2}
result = dict(zip(t[::2], t[1::2]))
print(result)  # {1: 2} (ค่า 3 ถูกทิ้ง)