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

Tạo Ordered Dictionary trong Python

OrderedDict (module collections) nhớ thứ tự thêm key-value pair.

Ví dụ

>>> from collections import OrderedDict
>>> od = OrderedDict(d.items())
>>> od
OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])
>>> t = od.popitem()
>>> t
('orange', 2)

Lưu ý: Python 3.7+ dict built-in đã giữ insertion order, OrderedDict vẫn hữu ích cho các method đặc thù (move_to_end, popitem(last=False)).