如同這個數據結構的名稱所說的那樣,它記錄了每個鍵值對添加的順序。
1
2
3
4
5
6
|
d
=
OrderedDict()
d[
'a'
]
=
1
d[
'b'
]
=
10
d[
'c'
]
=
8
for
letter
in
d:
print
letter
|
輸出:
1
2
3
|
a
b
c
|
如果初始化的時候同時傳入多個參數,它們的順序是隨機的,不會按照位置順序存儲。
1
2
|
>>> d
=
OrderedDict(a
=
1
, b
=
2
, c
=
3
)
OrderedDict([(
'a'
,
1
), (
'c'
,
3
), (
'b'
,
2
)])
|
除了和正常的 dict 相同的方法之外,OrderedDict 還提供了和順序相關的操作: + popitem(): 返回最后一個插入的鍵值對,如果 popitem(last=False) 將返回第一個插入的鍵值對 + reversed:返回一個逆序的 OrderedDict
實例
其實,OrderedDict可以看作是一個字典子類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import
collections
print
'Regular dictionary:'
d
=
{}
d[
'a'
]
=
'A'
d[
'b'
]
=
'B'
d[
'c'
]
=
'C'
for
k, v
in
d.items():
print
k, v
print
'\nOrderDict:'
d
=
collections.OrderedDict()
d[
'a'
]
=
'A'
d[
'b'
]
=
'B'
d[
'c'
]
=
'C'
for
k, v
in
d.items():
print
k, v
|
常規dict並不跟蹤插入順序,迭代處理會根據鍵在散列表中存儲的順序來生成值。在OrderDict中則相反,它會記住元素插入的順序,並在創建迭代器時使用這個順序。
1
2
3
4
5
6
7
8
|
Regular dictionary:
a A
c C
b B
OrderDict:
a A
b B
c C
|
常規dict在檢查相等性是會查看其內容,OrderDict中還會考慮元素增加的順序。