Dictionary: key–value pairs Dictionary: คู่ key–value

Build a dict; read / write / delete by indexing; membership (in / not in) and len() สร้าง dict, อ่าน/เขียน/ลบด้วย indexing, membership (in / not in) และ len()

A dict (dictionary) is a collection of key–value pairs. You use a key to find its value quickly — you do not scan position by position like a list. Keys must be unique and must be values that cannot change (immutable), such as a string or a number. Values can repeat and can be changed.

dict (dictionary) คือคอลเลกชันของคู่ key–value ใช้ key หา value ได้เร็ว — ไม่ต้องไล่ทีละตำแหน่งแบบ list key ต้องunique และเป็นค่าที่เปลี่ยนไม่ได้ (immutable) เช่น สตริงหรือตัวเลข ส่วน value ซ้ำกันได้และเปลี่ยนได้

1 Dictionary literals 1 Dictionary Literals

Write a dict with curly braces {key: value, ...}, separating pairs with commas. {} is an empty dict — no key–value pairs yet.

เขียน dict ด้วยวงเล็บปีกกา {key: value, ...} คั่นคู่ด้วยจุลภาค {} คือ dict ว่าง — ยังไม่มีคู่ key–value

[1]
[output]
{1: 'one', 2: 'two'}
{}

2 Indexing: read a value 2 Indexing อ่านค่า

Use d[key] to read the value bound to that key. If the key is missing, this raises an error (unlike a list, which uses a position index).

ใช้ d[key] อ่าน value ที่ผูกกับ key นั้น ถ้าไม่มี key จะเกิดข้อผิดพลาด (ต่างจาก list ที่ใช้ดัชนีตำแหน่ง)

[2]
[output]
85

3 Add and change a value by indexing 3 เพิ่มและแก้ค่าด้วย indexing

Assign on the left with d[key] = .... If the key is not there yet, this adds a new pair; if it already exists, this changes that pair's value.

กำหนดค่าทางซ้ายด้วย d[key] = ... ถ้ายังไม่มี key นั้นจะเพิ่มคู่ใหม่ ถ้ามีอยู่แล้วจะแก้ value ของคู่นั้น

[3]
[output]
{'math': 92, 'eng': 90, 'sci': 78}

4 Delete with del 4 ลบด้วย del

del d[key] removes the whole key–value pair from the dict. After deleting, that key no longer exists.

คำสั่ง del d[key] ลบทั้งคู่ key–value ออกจาก dict หลังลบแล้ว key นั้นจะไม่มีอยู่แล้ว

[4]
[output]
{'pen': 12, 'pad': 8}

5 Membership (in / not in) 5 Membership (in / not in)

With a dict, in / not in check whether a value is a key — not a value. For example, even if a value is 0, if 0 is not a key you get False.

in / not in กับ dict ตรวจว่ามีค่าเป็นkey หรือไม่ — ไม่ได้เช็ค value เช่น แม้มี value เป็น 0 แต่ถ้า 0 ไม่ใช่ key จะได้ False

[5]
[output]
True
False
True

6 len()

len(d) counts the number of pairs in the dict. An empty dict gives 0.

len(d) นับจำนวนคู่ key–value ใน dict dict ว่างได้ 0

[6]
[output]
2
0

7 Safe reading with get() 7 อ่านค่าอย่างปลอดภัยด้วย get()

d.get(key) reads a value like d[key] but returns None instead of raising an error when the key is missing. d.get(key, default) returns default instead. This is useful when you are not sure whether a key exists.

d.get(key) อ่านค่าคล้าย d[key] แต่ถ้าไม่มี key จะคืน None แทนการเกิดข้อผิดพลาด ส่วน d.get(key, default) จะคืน default แทน เหมาะเมื่อไม่แน่ใจว่ามี key นั้นหรือไม่

[7]
[output]
85
None
0

8 A price list and an order 8 รายการราคากับใบสั่งซื้อ

A dictionary is a natural way to look things up by name. Here the menu maps each item to its price, and an order is a list of item names. The for loop (covered in a later lesson) visits each ordered item, prices[item] looks up its price, and total += ... adds it to the running total.

dictionary เหมาะกับการค้นหาข้อมูลจากชื่อ ตัวอย่างนี้ใช้ dictionary เก็บราคาสินค้าแต่ละรายการ และใช้ list เก็บรายการที่สั่ง ลูป for (จะเรียนในบทถัดไป) จะไล่ทีละรายการ prices[item] ค้นราคา และ total += ... บวกเข้ายอดรวม

[8]
[output]
Total = 240 baht

9 Common mistakes 9 ข้อผิดพลาดที่พบบ่อย

  1. Reading a missing key with []. d["sci"] raises KeyError when "sci" is not a key. Check with in or use get() instead.
  2. อ่านคีย์ที่ไม่มีด้วย [] d["sci"] จะเกิด KeyError ถ้าไม่มีคีย์ "sci" ให้ตรวจด้วย in หรือใช้ get() แทน
  3. Duplicate keys. Keys are unique: if you write the same key twice, the later value silently replaces the earlier one (see line 1 of the demo).
  4. คีย์ซ้ำ คีย์ต้องไม่ซ้ำกัน ถ้าเขียนคีย์เดียวกันสองครั้ง ค่าหลังจะเขียนทับค่าแรกโดยไม่มีข้อความเตือน (ดูบรรทัดแรกของตัวอย่าง)
  5. Thinking get() adds the key. d.get("z", 0) only returns a default; the dictionary is unchanged, as the last print shows.
  6. คิดว่า get() เพิ่มคีย์ให้ d.get("z", 0) แค่คืนค่าเริ่มต้น dictionary ไม่เปลี่ยน ดังผลลัพธ์ของ print บรรทัดสุดท้าย
  7. Unhashable keys. A list cannot be a key (TypeError); use text, numbers, or tuples as keys.
  8. ใช้ค่าที่เป็น key ไม่ได้ list เป็นคีย์ไม่ได้ (TypeError) ให้ใช้ข้อความ ตัวเลข หรือ tuple เป็นคีย์
[9]
[output]
{'a': 2}
0
{'a': 2}

10 Think further 10 แบบฝึกคิดต่อ

Try these yourself in the Run boxes above (or in Google Colab):

ลองทำเองในกล่อง Run ด้านบน (หรือใน Google Colab):

  1. Create a dictionary of three friends and their ages, then print one age by indexing.
  2. สร้าง dictionary ของเพื่อน 3 คนพร้อมอายุ แล้วพิมพ์อายุของคนหนึ่งด้วย index
  3. Add a fourth friend and change one age, then print the whole dictionary.
  4. เพิ่มเพื่อนคนที่สี่และแก้อายุของคนหนึ่ง แล้วพิมพ์ทั้ง dictionary
  5. Print the age of a friend who is not in the dictionary without causing an error and show "unknown" instead. Hint: get() with a default.
  6. พิมพ์อายุของเพื่อนที่ไม่มีใน dictionary โดยไม่ให้เกิด error และให้แสดง "unknown" แทน Hint: get() พร้อมค่าเริ่มต้น

Note: Run on this page is a JavaScript simulation, not real Python. For real Python, try Google Colab. หมายเหตุ: การกด Run บนหน้านี้เป็นการจำลองด้วย JavaScript ไม่ใช่ Python จริง หากต้องการทดลอง Python จริง แนะนำ Google Colab

References References / แหล่งอ้างอิง

Sources used for this lesson:

แหล่งที่ใช้ประกอบเนื้อหาในบทนี้:

  1. G3 Computing Textbook (O-Level/G3, Fourth Version, 2024) — Curriculum Planning and Development Division, Ministry of Education, Singapore — Section 4.13 Dictionaries (chapter outline and key concepts) Section 4.13 Dictionaries (โครงหัวข้อและแนวคิดหลักของบท)
  2. Mapping Types — dict — Built-in Types — Mapping Types (literals, indexing, membership, get) (literals, indexing, membership, get)
  3. The del statement — Python Language Reference — del (del d[key])
  4. Built-in Functions — len — Built-in Functions — len (len(d))

End-of-lesson quizแบบฝึกหัดท้ายบท

ตอบแล้ว 0 / 10

ข้อ 1

1 / 10

What is a dict in Python?dict ใน Python คืออะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (A) A collection of key-value pairsคอลเลกชันคู่ key–value

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) A collection of key-value pairsคอลเลกชันคู่ key–value
    Correct! A dict stores key-value pairs and looks up a value by its key.ถูกต้อง! dict เก็บคู่ key–value และใช้ key หาค่าได้
  • (B) A sequence ordered only by position indexลำดับค่าที่เรียงด้วยดัชนีตำแหน่งเท่านั้น
    Wrong: that is closer to a list, not a dict.ผิด: นั่นใกล้เคียงกับ list ไม่ใช่ dict
  • (C) A numbers-only data typeชนิดข้อมูลตัวเลขเท่านั้น
    Wrong: a dict is a collection, not a number type.ผิด: dict เป็นคอลเลกชัน ไม่ใช่ชนิดตัวเลข
  • (D) An immutable stringสตริงที่เปลี่ยนไม่ได้
    Wrong: a string is a str, not a dict.ผิด: สตริงเป็น str ไม่ใช่ dict

ข้อ 2

2 / 10

With d = {"a": 1, "b": 2}, what is d["b"]?จาก d = {"a": 1, "b": 2} ผลของ d["b"] คือข้อใด?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (C) 22

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) "b""b"
    Wrong: "b" is the key, not the value read.ผิด: "b" คือ key ไม่ใช่ค่าที่อ่านได้
  • (B) 11
    Wrong: 1 is the value of key "a".ผิด: 1 คือค่าของ key "a"
  • (C) 22
    Correct! d["b"] reads the value of key "b", which is 2.ถูกต้อง! d["b"] อ่าน value ของ key "b" ได้ 2
  • (D) {"b": 2}{"b": 2}
    Wrong: indexing returns a value, not a sub-dict.ผิด: indexing คืน value ไม่ใช่ dict ย่อย

ข้อ 3

3 / 10

What does in check on a dict?in กับ dict ตรวจอะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (B) Whether a value is present as a keyว่ามีค่าเป็น key หรือไม่

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) Whether a value is present as a valueว่ามีค่าเป็น value หรือไม่
    Wrong: in on a dict does not check values directly.ผิด: in กับ dict ไม่ได้เช็ค value โดยตรง
  • (B) Whether a value is present as a keyว่ามีค่าเป็น key หรือไม่
    Correct! in / not in check whether a key is present.ถูกต้อง! in / not in ตรวจว่ามี key หรือไม่
  • (C) Whether the length equals a given numberว่าความยาวเท่ากับจำนวนที่ระบุหรือไม่
    Wrong: length uses len(), not in.ผิด: ความยาวใช้ len() ไม่ใช่ in
  • (D) Whether the dict is emptyว่า dict ว่างหรือไม่
    Wrong: checking emptiness is not what in is for.ผิด: การตรวจว่างไม่ใช่หน้าที่หลักของ in

ข้อ 4

4 / 10

After scores = {"Ann": 80} then scores["Ann"] = 90, what is scores["Ann"]?หลัง scores = {"Ann": 80} แล้ว scores["Ann"] = 90 ค่า scores["Ann"] เป็นข้อใด?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (D) 9090

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) 8080
    Wrong: 80 is the old value before it was changed.ผิด: 80 เป็นค่าเดิมก่อนถูกแก้
  • (B) "Ann""Ann"
    Wrong: "Ann" is the key, not the value.ผิด: "Ann" คือ key ไม่ใช่ value
  • (C) NoneNone
    Wrong: assigning by index does not make it None.ผิด: การกำหนดค่าด้วย indexing ไม่ได้ทำให้เป็น None
  • (D) 9090
    Correct! Reassigning key "Ann" gives 90.ถูกต้อง! กำหนดค่าใหม่ให้ key "Ann" แล้วได้ 90

ข้อ 5

5 / 10

What does len({}) give?len({}) ได้ค่าเท่าไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (A) 00

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) 00
    Correct! An empty dict has no pairs, so it is 0.ถูกต้อง! dict ว่างไม่มีคู่ key–value จึงได้ 0
  • (B) 11
    Wrong: {} has no pairs at all.ผิด: {} ไม่มีคู่ใดเลย
  • (C) NoneNone
    Wrong: len() returns an integer, not None.ผิด: len() คืนจำนวนเต็ม ไม่ใช่ None
  • (D) {}{}
    Wrong: len() returns a number, not a dict.ผิด: len() คืนตัวเลข ไม่คืน dict

ข้อ 6

6 / 10

What does del d["k"] do?del d["k"] ทำอะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (C) Removes the whole key-value pair from the dictลบทั้งคู่ key–value ออกจาก dict

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) Sets the value of key "k" to 0ตั้งค่าของ key "k" เป็น 0
    Wrong: del removes the whole pair; it does not set it to 0.ผิด: del ลบทั้งคู่ ไม่ได้ตั้งค่าเป็น 0
  • (B) Removes only the value but keeps the keyลบเฉพาะ value แต่คง key ไว้
    Wrong: del removes both the key and the value.ผิด: del ลบทั้งคู่ key และ value
  • (C) Removes the whole key-value pair from the dictลบทั้งคู่ key–value ออกจาก dict
    Correct! After del, key "k" no longer exists.ถูกต้อง! หลัง del key "k" จะไม่มีอยู่แล้ว
  • (D) Deletes the entire dictลบ dict ทั้งก้อน
    Wrong: del d["k"] removes only that pair, not the whole dict.ผิด: del d["k"] ลบเฉพาะคู่นั้น ไม่ใช่ทั้ง dict

ข้อ 7

7 / 10

With d = {"math": 85}, what is d.get("sci")?จาก d = {"math": 85} ผลของ d.get("sci") คือข้อใด?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (B) NoneNone

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) An error, because key "sci" is missingError เพราะไม่มี key "sci"
    Wrong: get() does not raise an error for a missing key.ผิด: get() ไม่ทำให้เกิด error เมื่อไม่มี key
  • (B) NoneNone
    Correct! get() returns None for a missing key with no default given.ถูกต้อง! get() คืน None เมื่อไม่มี key และไม่ได้ระบุ default
  • (C) 00
    Wrong: you must write d.get("sci", 0) to get 0.ผิด: ต้องเขียน d.get("sci", 0) จึงจะได้ 0
  • (D) 8585
    Wrong: 85 is the value of key "math".ผิด: 85 คือค่าของ key "math"

ข้อ 8

8 / 10

To read the "sci" score, getting 0 if it is not there yet, what should you write?ต้องการอ่านคะแนนวิชา "sci" โดยได้ 0 ถ้ายังไม่มี ควรเขียนอย่างไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (A) d.get("sci", 0)d.get("sci", 0)

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) d.get("sci", 0)d.get("sci", 0)
    Correct! The second argument is the default value.ถูกต้อง! อาร์กิวเมนต์ตัวที่สองคือค่า default
  • (B) d["sci"]d["sci"]
    Wrong: this raises an error if the key is missing.ผิด: จะเกิด error ถ้าไม่มี key
  • (C) d.get("sci")d.get("sci")
    Wrong: this returns None, not 0, for a missing key.ผิด: คืน None ไม่ใช่ 0 ถ้าไม่มี key
  • (D) d.get(0, "sci")d.get(0, "sci")
    Wrong: the key and default are swapped.ผิด: สลับตำแหน่ง key กับ default

ข้อ 9

9 / 10

Which statement about dict keys is correct?ข้อใดถูกเกี่ยวกับ key ของ dict?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (D) A key must be unique and immutable, e.g. a string or a numberkey ต้อง unique และเป็นค่าที่เปลี่ยนไม่ได้ เช่น สตริงหรือตัวเลข

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) Keys can repeatkey ซ้ำกันได้
    Wrong: keys must be unique.ผิด: key ต้อง unique
  • (B) A key must be a listkey ต้องเป็น list เท่านั้น
    Wrong: a list is mutable and cannot be a key.ผิด: list เปลี่ยนได้ ใช้เป็น key ไม่ได้
  • (C) Values must be unique but keys can repeatvalue ต้อง unique แต่ key ซ้ำได้
    Wrong: it is reversed — keys must be unique, values can repeat.ผิด: สลับกัน — key ต้อง unique ส่วน value ซ้ำได้
  • (D) A key must be unique and immutable, e.g. a string or a numberkey ต้อง unique และเป็นค่าที่เปลี่ยนไม่ได้ เช่น สตริงหรือตัวเลข
    Correct! Exactly as the lesson explains.ถูกต้อง! ตามที่บทอธิบาย

ข้อ 10

10 / 10

With scores = {"math": 85, "eng": 90}, what does scores["sci"] = 78 do?จาก scores = {"math": 85, "eng": 90} แล้ว scores["sci"] = 78 ทำให้เกิดอะไร?

เฉลย / Answerซ่อนเฉลย / Hide

เฉลย / Answer: (B) Adds the new pair "sci": 78 to the dictเพิ่มคู่ใหม่ "sci": 78 เข้า dict

คำอธิบายแต่ละตัวเลือก / Explanation for each choice

  • (A) An error, because key "sci" does not exist yetError เพราะยังไม่มี key "sci"
    Wrong: assigning adds the new key automatically.ผิด: การกำหนดค่าจะเพิ่ม key ใหม่ให้เอง
  • (B) Adds the new pair "sci": 78 to the dictเพิ่มคู่ใหม่ "sci": 78 เข้า dict
    Correct! If the key is not there, a new pair is added.ถูกต้อง! ถ้ายังไม่มี key จะเพิ่มคู่ใหม่
  • (C) Changes "math" to 78แก้ค่าของ "math" เป็น 78
    Wrong: only key "sci" is affected.ผิด: กระทบเฉพาะ key "sci"
  • (D) Deletes the dict and makes a new oneลบ dict แล้วสร้างใหม่
    Wrong: the same dict stays; only a new pair is added.ผิด: dict เดิมยังอยู่ เพียงเพิ่มคู่ใหม่