Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Thêm cặp key-value vào Dictionary Python


Dictionary Python là ánh xạ key-value không thứ tự (Python <3.7) hoặc có thứ tự thêm (3.7+). 3 cách thêm phần tử.

Cách 1: Gán trực tiếp qua key (Subscript) - Phổ biến nhất

country_codes = {"India": 91, "UK": 44, "USA": 1}
print("Trước:", country_codes)

country_codes["Spain"] = 34
print("Sau thêm Spain:", country_codes)

Kết quả

Trước: {'India': 91, 'UK': 44, 'USA': 1}
Sau thêm Spain: {'India': 91, 'UK': 44, 'USA': 1, 'Spain': 34}

Cách 2: update() - Thêm một hoặc nhiều cặp

country_codes = {"India": 91, "UK": 44, "USA": 1, "Spain": 34}

# Thêm 1 cặp
country_codes.update({"Germany": 49})
print("Sau update 1:", country_codes)

# Thêm nhiều cặp (iterable của tuple/list)
country_codes.update([("Austria", 43), ("Russia", 7)])
print("Sau update nhiều:", country_codes)

Kết quả

Sau update 1: {'India': 91, 'UK': 44, 'USA': 1, 'Spain': 34, 'Germany': 49}
Sau update nhiều: {'India': 91, 'UK': 44, 'USA': 1, 'Spain': 34, 'Germany': 49, 'Austria': 43, 'Russia': 7}

Cách 3: Merge 2 dictionary (Python 3.9+)

dict1 = {"India": 91, "UK": 44}
dict2 = {"Germany": 49, "Russia": 7}

# Toán tử | (union) - Tạo dict MỚI
merged = dict1 | dict2
print("Merged (|):", merged)

# Toán tử |= (in-place update) - Sửa dict1
dict1 |= dict2
print("dict1 after |=": dict1)

Cách 3b: Python < 3.9 - dict unpacking

merged = {**dict1, **dict2}  # Tạo dict mới
# Hoặc
dict1.update(dict2)          # In-place

Kết luận

  • Thêm 1 key: d[key] = value (nhanh, rõ ràng).
  • Thêm nhiều: d.update(...).
  • Merge 2 dict: d1 | d2 (3.9+) hoặc {**d1, **d2}.
  • Key trùng: giá trị sau ghi đè giá trị trước.