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

Cắt ngắn (truncate) Dictionary tại độ dài cho trước trong Python

Dùng itertools.islice() trên dict.items() để lấy N cặp đầu tiên, sau đó xây dict mới.

Ví dụ: Giữ 3 cặp đầu

import itertools

D1 = {"pen": 25, "pencil": 10, "book": 100, "sharpner": 5, "eraser": 5}
D2 = dict(itertools.islice(D1.items(), 3))
print(D2)  # {'pen': 25, 'pencil': 10, 'book': 100}

Giải thích

  • D1.items() → view các cặp (key, value) theo thứ tự insertion (Python 3.7+).
  • islice(iterable, stop) — lấy stop phần tử đầu.
  • dict(...) — xây dictionary mới từ iterator.

Python 3.8+: Dùng dict comprehension với enumerate

D2 = {k: v for i, (k, v) enumerate(D1.items()) if i < 3}

Lưu ý: Trước Python 3.7, dict không bảo đảm thứ tự; kết quả có thể không xác định.