2020年4月25日 星期六

Python - How to sort dictionary? OrderedDict

#Import OrderedDict
from collections import OrderedDict

[OrderedDict Operation]
- Add Key/Value
D=OrderedDict()
D[1]=3
D[7]=1
D[2]=5
D[9]=7
#Dict status  OrderedDict([(1, 3), (7, 1), (2, 5), (9, 7)])

- Change key to Last
>>> D.move_to_end(1)
#Dict status  OrderedDict([(7, 1), (2, 5), (9, 7), (1, 3)])

- Pop Dict Item
>>> D.popitem()
(1, 3)
#Dict status  OrderedDict([(7, 1), (2, 5), (9, 7)])

- Pop first Dict Item
>>> D.popitem(last=False)
(7, 1)
#Dict status OrderedDict([(2, 5), (9, 7)])