python模塊簡介之有序字典(OrderedDict)
有序字典-OrderedDict簡介
示例
有序字典和通常字典類似,只是它可以記錄元素插入其中的順序,而一般字典是會以任意的順序迭代的。參見下面的例子:
import collections print 'Regular dictionary:' d = {} d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' d['d'] = 'D' d['e'] = 'E' for k, v in d.items(): print k, v print '\nOrderedDict:' d = collections.OrderedDict() d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' d['d'] = 'D' d['e'] = 'E' for k, v in d.items(): print k, v
運(yùn)行結(jié)果如下:
-> python test7.py Regular dictionary: a A c C b B e E d D OrderedDict: a A b B c C d D e E
可以看到通常字典不是以插入順序遍歷的。
相等性
判斷兩個有序字段是否相等(==)需要考慮元素插入的順序是否相等
import collections print 'dict :', d1 = {} d1['a'] = 'A' d1['b'] = 'B' d1['c'] = 'C' d1['d'] = 'D' d1['e'] = 'E' d2 = {} d2['e'] = 'E' d2['d'] = 'D' d2['c'] = 'C' d2['b'] = 'B' d2['a'] = 'A' print d1 == d2 print 'OrderedDict:', d1 = collections.OrderedDict() d1['a'] = 'A' d1['b'] = 'B' d1['c'] = 'C' d1['d'] = 'D' d1['e'] = 'E' d2 = collections.OrderedDict() d2['e'] = 'E' d2['d'] = 'D' d2['c'] = 'C' d2['b'] = 'B' d2['a'] = 'A' print d1 == d2
運(yùn)行結(jié)果如下:
-> python test7.py dict : True OrderedDict: False
而當(dāng)判斷一個有序字典和其它普通字典是否相等只需判斷內(nèi)容是否相等。
注意
OrderedDict 的構(gòu)造器或者 update() 方法雖然接受關(guān)鍵字參數(shù),但因?yàn)閜ython的函數(shù)調(diào)用會使用無序的字典來傳遞參數(shù),所以關(guān)鍵字參數(shù)的順序會丟失,所以創(chuàng)造出來的有序字典不能保證其順序。
參考資料
https://docs.python.org/2/library/collections.html#collections.OrderedDict
https://pymotw.com/2/collections/ordereddict.html
相關(guān)文章
基于Keras 循環(huán)訓(xùn)練模型跑數(shù)據(jù)時內(nèi)存泄漏的解決方式
這篇文章主要介紹了基于Keras 循環(huán)訓(xùn)練模型跑數(shù)據(jù)時內(nèi)存泄漏的解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨想過來看看吧2020-06-06python?Matplotlib繪制炫酷柱狀圖的藝術(shù)與技巧大全
柱狀圖(Bar Plot)是一種常用的數(shù)據(jù)可視化方式,用于顯示各個類別之間的比較,下面這篇文章主要給大家介紹了關(guān)于python?Matplotlib繪制炫酷柱狀圖的藝術(shù)與技巧大全,需要的朋友可以參考下2024-03-03Pytorch參數(shù)注冊和nn.ModuleList nn.ModuleDict的問題
這篇文章主要介紹了Pytorch參數(shù)注冊和nn.ModuleList nn.ModuleDict的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01python獲取一組數(shù)據(jù)里最大值max函數(shù)用法實(shí)例
這篇文章主要介紹了python獲取一組數(shù)據(jù)里最大值max函數(shù)用法,實(shí)例分析了max函數(shù)的使用技巧,需要的朋友可以參考下2015-05-05Python實(shí)現(xiàn)發(fā)送與接收郵件的方法詳解
這篇文章主要介紹了Python實(shí)現(xiàn)發(fā)送與接收郵件的方法,結(jié)合實(shí)例形式分析了Python基于smtplib庫使用SMTP協(xié)議進(jìn)行郵件發(fā)送及基于poplib庫使用POP3服務(wù)器接收郵件的相關(guān)操作技巧,需要的朋友可以參考下2018-03-03