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

การเพิ่ม Dictionary เข้าไปใน Tuple ใน Python

Add Dictionary to Tuple ใน Python

เมื่อต้องการเพิ่ม Dictionary เข้าไปใน Tuple สามารถใช้เมธอด list(), append() และ tuple() ได้

เหตุผลที่ต้องแปลงเป็น List ก่อน

Tuple เป็น Immutable ไม่สามารถเพิ่ม/ลบ/แก้ไขข้อมูลได้โดยตรง จึงต้องแปลงเป็น List (Mutable) ก่อน แล้วค่อยแปลงกลับเป็น Tuple

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

my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4)
print("The tuple is : ")
print(my_tuple_1)

my_dict = {"Hey": 11, "there": 31, "Jane": 23}
print("The dictionary is : ")
print(my_dict)

# แปลง Tuple -> List -> Append Dict -> กลับเป็น Tuple
my_tuple_1 = list(my_tuple_1)
my_tuple_1.append(my_dict)
my_tuple_1 = tuple(my_tuple_1)

print("The tuple after adding the dictionary elements is : ")
print(my_tuple_1)

ผลลัพธ์

The tuple is : (7, 8, 0, 3, 45, 3, 2, 22, 4)
The dictionary is : {'Hey': 11, 'there': 31, 'Jane': 23}
The tuple after adding the dictionary elements is : (7, 8, 0, 3, 45, 3, 2, 22, 4, {'Hey': 11, 'there': 31, 'Jane': 23})

คำอธิบาย

  • กำหนด Tuple และแสดงผล
  • กำหนด Dictionary และแสดงผล
  • แปลง Tuple เป็น List ด้วย list()
  • ใช้ append() เพิ่ม Dictionary เข้าไปท้าย List
  • แปลง List กลับเป็น Tuple ด้วย tuple()
  • แสดงผล Tuple ใหม่ที่มี Dictionary เป็น Element สุดท้าย

วิธีอื่น: Tuple Concatenation

# สร้าง Tuple ใหม่โดยรวม Tuple เดิมกับ Tuple ที่มี Dict อยู่คนเดียว
my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4)
my_dict = {"Hey": 11, "there": 31, "Jane": 23}
new_tuple = my_tuple_1 + (my_dict,)
print(new_tuple)
# (7, 8, 0, 3, 45, 3, 2, 22, 4, {'Hey': 11, 'there': 31, 'Jane': 23})

หมายเหตุ: วิธี Concurrency นี้สร้าง Tuple ใหม่ ไม่ได้แก้ Tuple เดิม (เพราะ Tuple Immutable)