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

แปลงทัพเพิลแบบซ้อน (Nested Tuple) เป็นดิกชันนารีที่มีคีย์กำหนดเองใน Python


เมื่อต้องการแปลงทัพเพิลที่มีทัพเพิลย่อยอยู่ภายใน เป็นลิสต์ของดิกชันนารีที่มีคีย์เฉพาะ สามารถใช้ List Comprehension

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

my_tuple = ((6, 'Will', 13), (2, 'Mark', 15), (9, 'Rob', 12))
print("The tuple is:")
print(my_tuple)

my_result = [{'key': sub[0], 'value': sub[1], 'id': sub[2]} for sub in my_tuple]
print("The converted dictionary is:")
print(my_result)

ผลลัพธ์

The tuple is: ((6, 'Will', 13), (2, 'Mark', 15), (9, 'Rob', 12))
The converted dictionary is: [{'key': 6, 'value': 'Will', 'id': 13}, {'key': 2, 'value': 'Mark', 'id': 15}, {'key': 9, 'value': 'Rob', 'id': 12}]

คำอธิบาย

  • กำหนดทัพเพิลที่มีทัพเพิลย่อย 3 ค่า (key, value, id)

  • ใช้ List Comprehension วนลูปผ่านแต่ละทัพเพิลย่อย (sub)

  • สร้างดิกชันนารีใหม่โดยแมปค่า: sub[0]→key, sub[1]→value, sub[2]→id

  • ผลลัพธ์เป็นลิสต์ของดิกชันนารี