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

Python Dictionaries: คู่มือครบวงจร สร้าง, เข้าถึง, Loop, CRUD Operations

Dictionary (Dict) ใน Python เป็น Key-Value Mapping 类似 Java Map ใช้ Curly Braces {} Key ต้องเป็น Immutable (String, Number, Tuple)

1. สร้าง Dictionary

# Literal Syntax
datedict = {
    "date": 13,
    "month": "January",
    "year": 1970
}

# dict() Constructor
datedict = dict(date=13, month="January", year=1970)
datedict = dict([("date", 13), ("month", "January")])

# From Keys (ค่า Default เดียวกัน)
keys = ['a', 'b', 'c']
d = dict.fromkeys(keys, 0)  # {'a': 0, 'b': 0, 'c': 0}

2. เข้าถึง Items

datedict = {"date": 13, "month": "January", "year": 1970}

# [] - โยน KeyError ถ้าไม่มี Key
print(datedict["date"])        # 13

# .get() - คืน None (หรือ Default) ถ้าไม่มี Key ✅ แนะนำ
print(datedict.get("date"))    # 13
print(datedict.get("missing")) # None
print(datedict.get("missing", "N/A"))  # "N/A"

3. แก้ไข/เพิ่ม Items

datedict["date"] = 20          # แก้ไข
datedict["season"] = "winter"  # เพิ่มใหม่

# update() - เพิ่มหลายตัวพร้อมกัน
datedict.update({"day": "Monday", "week": 3})

4. วนลูป Dictionary

datedict = {"date": 13, "month": "January", "year": 1970}

# Keys Only
for key in datedict:
    print(key)
# date, month, year

# Values Only
for value in datedict.values():
    print(value)
# 13, January, 1970

# Keys และ Values (Items) ✅ แนะนำ
for key, value in datedict.items():
    print(f"{key}: {value}")
# date: 13
# month: January
# year: 1970

5. ความยาว Dictionary

len(datedict)  # 3

6. ลบ Items

datedict = {"date": 13, "month": "January", "year": 1970, "season": "winter"}

# pop() - ลบและคืนค่า Value
value = datedict.pop("season")  # "winter"
# pop() โยน KeyError ถ้าไม่มี Key - ใช้ pop(key, default)

# del - ลบโดยไม่คืนค่า
del datedict["month"]

# clear() - ลบทั้งหมด
datedict.clear()  # {}

# del variable - ลบตัวแปร Dict ทั้งตัว
del datedict

7. Dictionary Methods Cheatsheet

Methodคำอธิบายตัวอย่าง
get(key, default)เข้าถึงปลอดภัยd.get('x', 0)
setdefault(key, default)Set ถ้ายังไม่มี Key นั้นd.setdefault('x', []).append(1)
update(other)Merge Dict อื่นเข้าไปd1.update(d2)
pop(key, default)ลบและคืนค่าd.pop('x')
popitem()ลบและคืนค่า Item สุดท้าย (3.7+)d.popitem()
keys()View ของ Keyslist(d.keys())
values()View ของ Valueslist(d.values())
items()View ของ (Key, Value)list(d.items())
copy()Shallow Copyd.copy()

8. Advanced Patterns

Merge Dictionaries (Python 3.9+)

d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}

# | Operator (3.9+)
merged = d1 | d2      # {'a': 1, 'b': 3, 'c': 4} (d2 win)

# |= In-place update (3.9+)
d1 |= d2              # d1 กลายเป็น {'a': 1, 'b': 3, 'c': 4}

# ** Unpacking (3.5+)
merged = {**d1, **d2} # {'a': 1, 'b': 3, 'c': 4}

Dictionary Comprehension

# สร้าง Dict จาก List
words = ['apple', 'banana', 'cherry']
word_lengths = {word: len(word) for word in words}
# {'apple': 5, 'banana': 6, 'cherry': 6}

# Filter
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

บทความเกี่ยวข้อง