OrderedDict继承于dict,当插入key时顺序就已经确定了。如插入一个key存在的项,key的顺序不会改变。如果先删除再插入,则会移动到右边。
In [5]: d = OrderedDict({'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2})
In [6]: d
Out[6]: OrderedDict([('pear', 1), ('banana', 3), ('apple', 4), ('orange', 2)])
In [7]: d.update({'d':1})
In [8]: d
Out[8]:
OrderedDict([('pear', 1),
('banana', 3),
('apple', 4),
('orange', 2),
('d', 1)])
In [12]: d.update({"pear":99})
# 顺序没有改变
In [13]: d
Out[13]:
OrderedDict([('pear', 99),
('banana', 3),
('apple', 4),
('orange', 2),
('d', 1)])
In [15]: del d['pear']
In [16]: d
Out[16]: OrderedDict([('banana', 3), ('apple', 4), ('orange', 2), ('d', 1)])
In [17]: d.update({'pear': 99})
# 移动到右边
In [18]: d
Out[18]:
OrderedDict([('banana', 3),
('apple', 4),
('orange', 2),
('d', 1),
('pear', 99)])
In [22]: d.move_to_end('apple')
In [22]: " ".join(d.keys())
Out[22]: 'banana orange d pear apple'
# 当last=False时,将移动到最左边
In [23]: d.move_to_end('apple', last=False)
In [24]: " ".join(d.keys())
Out[24]: 'apple banana orange d pear'