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

การแปลง Tuple เป็น Dictionary ใน Python

ออบเจ็กต์ Dictionary สร้างได้ด้วยฟังก์ชัน dict() ซึ่งรับอาร์กิวเมนต์เป็น tuple ของ tuples โดยแต่ละ tuple ภายในเป็นคู่ key-value

ตัวอย่างพื้นฐาน

>> t = ((1, 'a'), (2, 'b'))
>>> dict(t)
{1: 'a', 2: 'b'}

สลับ Key และ Value

>> t = ((1, 'a'), (2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}

รูปแบบข้อมูลที่รองรับ

นอกจาก tuple of tuples แล้ว dict() ยังรับได้:

  • List of tuples: [(1, 'a'), (2, 'b')]
  • List of lists: [[1, 'a'], [2, 'b']]
  • Generator expression: ((k, v) for k, v in ...)
  • Keyword arguments: dict(a=1, b=2)

เงื่อนไข: Key ต้องเป็น immutable type (int, str, tuple, etc.) และไม่ซ้ำกัน