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

ไวยากรณ์การสร้าง Dictionary ใน Python

Dictionary เป็นคอลเลกชันของ key-value pairs แต่ละรายการประกอบด้วย value ที่เชื่อมโยงกับ key โดยใช้ : คั่น แล้วคั่นรายการด้วยจุลภาค และล้อมด้วยวงเล็บปีกกา {}

ไวยากรณ์พื้นฐาน

>> D1 = {
...     "name": "Raaj",
...     "age": 23,
...     "subjects": ["Phy", "Che", "maths"],
...     "GPA": 8.5
... }
>>> D1
{'name': 'Raaj', 'age': 23, 'subjects': ['Phy', 'Che', 'maths'], 'GPA': 8.5}

กฎสำคัญ

  • Key: ต้องเป็น immutable (int, str, tuple ที่มีแค่ immutable) และ ไม่ซ้ำกัน ใน dict เดียวกัน
  • Value: เป็นชนิดข้อมูลอะไรก็ได้ ซ้ำได้
  • Order: Python 3.7+ รักษาลำดับการ insert (insertion order)

วิธีสร้างอื่นๆ

>> # dict() constructor
>>> dict(name="Raaj", age=23)
{'name': 'Raaj', 'age': 23}

>>> # จาก list of tuples
>>> dict([('a', 1), ('b', 2)])
{'a': 1, 'b': 2}

>>> # dict comprehension
>>> {x: x**2 for x in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}