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

Python – รวม Tuple เป็น Key ของ Dictionary

เมื่อต้องการรวม tuple ให้เป็น key ของ dictionary สามารถใช้ลูป iteration และเมธอด join() ได้

ตัวอย่าง

my_list = [(("pyt", "is", "best"), 10), (("pyt", "cool"), 1), (("pyt", "is", "fun"), 15)]
print("The list is :")
print(my_list)
my_result = {}
for sub_list in my_list:
    my_result[" ".join(sub_list[0])] = sub_list[1]
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : [('pyt', 'is', 'best'), 10), (('pyt', 'cool'), 1), (('pyt', 'is', 'fun'), 15)]
The result is : {'pyt is best': 10, 'pyt cool': 1, 'pyt is fun': 15}

คำอธิบาย

  • กำหนดลิสต์ของ tuple ที่แต่ละตัวประกอบด้วย (tuple ของสตริง, ค่า)

  • สร้าง dictionary ว่าง

  • วนลูปผ่านลิสต์ ใช้ join() รวมสตริงใน tuple แรกด้วยช่องว่างเป็น key ค่า tuple ที่สองเป็น value

  • แสดงผลลัพธ์ dictionary ที่ได้