แปลง List เป็น Dictionary ใน Python
List เป็นโครงสร้างข้อมูลเชิงเส้น Dictionary เป็นโครงสร้างข้อมูล Key-Value Pairs โดย Key ต้องไม่ซ้ำกัน
ตัวอย่าง
List: [1, 2, 3, 4, 5, 6]
Dict: {1:2, 3:4, 5:6} # Index คู่เป็น Key, Index คี่เป็น Value
วิธีที่ 1: ใช้ Loop วนลูป
def convert(l):
dic = {}
for i in range(0, len(l), 2): # Step 2
dic[l[i]] = l[i+1]
return dic
ar = [1, 'Delhi', 2, 'Kolkata', 3, 'Bangalore', 4, 'Noida']
print(convert(ar))
ผลลัพธ์
{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}
คำอธิบาย
- Loop ก้าวละ 2 (
range(0, len(l), 2)) - Element Index คู่ (
l[i]) เป็น Key - Element Index คี่ (
l[i+1]) เป็น Value
วิธีที่ 2: ใช้ zip() (Pythonic)
def convert(l):
i = iter(l) # สร้าง Iterator
dic = dict(zip(i, i)) # zip จับคู่ Iterator กับตัวเอง
return dic
ar = [1, 'Delhi', 2, 'Kolkata', 3, 'Bangalore', 4, 'Noida']
print(convert(ar))
ผลลัพธ์
{1: 'Delhi', 2: 'Kolkata', 3: 'Bangalore', 4: 'Noida'}
ทำไม zip(i, i) ถึงทำงานได้?
iter(l) สร้าง Iterator หนึ่งเดียว zip(i, i) ดึงจาก Iterator ตัวเดียวกันสลับกัน: ตัวแรกไป Key, ตัวที่สองไป Value, ตัวที่สามไป Key... จนหมด
วิธีเพิ่มเติม
Dictionary Comprehension
ar = [1, 'Delhi', 2, 'Kolkata', 3, 'Bangalore', 4, 'Noida']
dic = {ar[i]: ar[i+1] for i in range(0, len(ar), 2)}
print(dic)
ใช้ slice
keys = ar[::2] # [1, 2, 3, 4]
values = ar[1::2] # ['Delhi', 'Kolkata', 'Bangalore', 'Noida']
dic = dict(zip(keys, values))
print(dic)
จัดการ List ความยาวคี่
def convert_safe(l):
"""Handle odd length list by ignoring last element"""
return {l[i]: l[i+1] for i in range(0, len(l)-1, 2)}
print(convert_safe([1, 2, 3])) # {1: 2} - Ignore 3