當前位置:成語大全網 - 新華字典 - python ordereddict 和字典的區別

python ordereddict 和字典的區別

class collections.OrderedDict([items])

Return an instance of a dict subclass, supporting the usual dict methods. An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end

翻譯過來就是實例化壹個dict的子類對象,該對象支持常用的dict方法。

壹個順序字典會記住它的key第壹次插入時的順序,如果壹新條目重寫了壹個已存在的條目,它第壹次插入的順序是不會改變的。刪除壹個條目並重新插入它,那它的順序將移動到末尾

所以從OrderedDict的字面意思就可以出來ordereddict是有順序(key被插入的先後順序)的字典,而普通的字典是無序的 。再請看下面的例子:

d= {'b':'bc','1':2,"a":"a","A":"A"}

print d.keys()輸出的結果是這樣的:['1', 'a', 'b', 'A']沒有按key的插入順序來

如果妳用ordereddict的話就不是這樣的

from collections import OrderedDict

od = OrderedDict()

od['b']='bc'

od['1']=2

od['a']='a'

od['A']='A'

print od.keys() 輸出的結果是按賦值的key的先後順序來輸出的['b', '1', 'a', 'A']

.