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: '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 ที่ใช้ดัชนีตำแหน่ง)
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 ของคู่นั้น
{'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 นั้นจะไม่มีอยู่แล้ว
{'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
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
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 นั้นหรือไม่
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 += ... บวกเข้ายอดรวม
Total = 240 baht
9 Common mistakes 9 ข้อผิดพลาดที่พบบ่อย
-
Reading a missing key with
[].d["sci"]raisesKeyErrorwhen"sci"is not a key. Check withinor useget()instead. -
อ่านคีย์ที่ไม่มีด้วย
[]d["sci"]จะเกิดKeyErrorถ้าไม่มีคีย์"sci"ให้ตรวจด้วยinหรือใช้get()แทน - 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).
- คีย์ซ้ำ คีย์ต้องไม่ซ้ำกัน ถ้าเขียนคีย์เดียวกันสองครั้ง ค่าหลังจะเขียนทับค่าแรกโดยไม่มีข้อความเตือน (ดูบรรทัดแรกของตัวอย่าง)
-
Thinking
get()adds the key.d.get("z", 0)only returns a default; the dictionary is unchanged, as the lastprintshows. -
คิดว่า
get()เพิ่มคีย์ให้d.get("z", 0)แค่คืนค่าเริ่มต้น dictionary ไม่เปลี่ยน ดังผลลัพธ์ของprintบรรทัดสุดท้าย -
Unhashable keys. A list cannot be a key (
TypeError); use text, numbers, or tuples as keys. -
ใช้ค่าที่เป็น key ไม่ได้ list เป็นคีย์ไม่ได้ (
TypeError) ให้ใช้ข้อความ ตัวเลข หรือ tuple เป็นคีย์
{'a': 2}
0
{'a': 2}
10 Think further 10 แบบฝึกคิดต่อ
Try these yourself in the Run boxes above (or in Google Colab):
ลองทำเองในกล่อง Run ด้านบน (หรือใน Google Colab):
- Create a dictionary of three friends and their ages, then print one age by indexing.
- สร้าง dictionary ของเพื่อน 3 คนพร้อมอายุ แล้วพิมพ์อายุของคนหนึ่งด้วย index
- Add a fourth friend and change one age, then print the whole dictionary.
- เพิ่มเพื่อนคนที่สี่และแก้อายุของคนหนึ่ง แล้วพิมพ์ทั้ง dictionary
-
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. -
พิมพ์อายุของเพื่อนที่ไม่มีใน 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:
แหล่งที่ใช้ประกอบเนื้อหาในบทนี้:
- 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 (โครงหัวข้อและแนวคิดหลักของบท)
-
Mapping Types — dict —
Built-in Types — Mapping Types
(literals, indexing, membership,
get) (literals, indexing, membership,get) -
The del statement —
Python Language Reference — del
(
del d[key]) -
Built-in Functions — len —
Built-in Functions — len
(
len(d))