Python中OrderedDict類如何使用,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
目標:創(chuàng)建一個字典,記錄幾對python詞語,使用OrderedDict類來寫,并按順序輸出。
寫完報錯:
[root@centos7 tmp]# python python_terms.py File "python_terms.py", line 9 from name,language in python_terms.items(): ^ SyntaxError: invalid syntax
代碼如下:
from collections import OrderedDict python_terms = OrderedDict() python_terms['key'] = 'vlaue' python_terms['if'] = 'match' python_terms['from'] = 'import' from name,language in python_terms.items(): print("python have many terms " + name.title() + language.title() + '.') ~
結果for循環(huán)的for寫成from了……總是出現(xiàn)簡單的錯誤。
最終,正確代碼如下:
from collections import OrderedDict python_terms = OrderedDict() python_terms['key'] = 'vlaue' python_terms['if'] = 'match' python_terms['from'] = 'import' for name,language in python_terms.items(): print("python have many terms " + name.title() + " " + language.title() + '.')
第一行,從模塊collections中導入OrderedDict類;
第二行,創(chuàng)建了OrderedDict類的一個實例,并將其存儲到python_terms中,也就是創(chuàng)建了一個空字典;
第三至五行,為字典添加鍵值對;
最后,循環(huán)輸出結果。
運行結果:
[root@centos7 tmp]# python python_terms.py python have many terms Key Vlaue. python have many terms If Match. python have many terms From Import.
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。
網(wǎng)頁標題:Python中OrderedDict類如何使用-創(chuàng)新互聯(lián)
分享URL:http://www.chinadenli.net/article32/jgjpc.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃、移動網(wǎng)站建設、品牌網(wǎng)站制作、服務器托管、商城網(wǎng)站、電子商務
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容