Dictionary เป็นคอลเลกชัน key-value pairs ไม่มี index จำลอง Key ไม่ซ้ำได้ → เพิ่ม Key ใหม่โดย Assignment แบบตรงไปตรงมา
ตัวอย่าง
>> D1 = {1: 'a', 2: 'b', 3: 'c', 'x': 1, 'y': 2, 'z': 3}
>>> D1[10] = 'z'
>>> D1
{1: 'a', 2: 'b', 3: 'c', 'x': 1, 'y': 2, 'z': 3, 10: 'z'}
พฤติกรรม
- Key ใหม่ (10) → เพิ่ม pair ใหม่
- Key มีอยู่แล้ว (เช่น D1[1] = 'new') → อัปเดต value เดิม
วิธีอื่น: update()
>> D1.update({20: 'new', 30: 'another'})
>>> D1
{1: 'a', 2: 'b', 3: 'c', 'x': 1, 'y': 2, 'z': 3, 10: 'z', 20: 'new', 30: 'another'}
Key ต้องเป็น Immutable
>> # OK >>> D1["string"] = 1 >>> D1[123] = 2 >>> D1[(1, 2)] = 3 >>> # Error - list ไม่ immutable >>> D1[[1, 2]] = 4 TypeError: unhashable type: 'list'