Python標(biāo)準(zhǔn)庫使用OrderedDict類的實(shí)例講解
目標(biāo):創(chuàng)建一個(gè)字典,記錄幾對(duì)python詞語,使用OrderedDict類來寫,并按順序輸出。
寫完報(bào)錯(cuò):
[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() + '.') ~
結(jié)果for循環(huán)的for寫成from了……總是出現(xiàn)簡單的錯(cuò)誤。
最終,正確代碼如下:
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中導(dǎo)入OrderedDict類;
第二行,創(chuàng)建了OrderedDict類的一個(gè)實(shí)例,并將其存儲(chǔ)到python_terms中,也就是創(chuàng)建了一個(gè)空字典;
第三至五行,為字典添加鍵值對(duì);
最后,循環(huán)輸出結(jié)果。
運(yùn)行結(jié)果:
[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.
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章
VSCode配合pipenv搞定虛擬環(huán)境的實(shí)現(xiàn)方法
這篇文章主要介紹了VSCode配合pipenv搞定虛擬環(huán)境的實(shí)現(xiàn)方法,文中通過圖文教程介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05python3新特性函數(shù)注釋Function Annotations用法分析
這篇文章主要介紹了python3新特性函數(shù)注釋Function Annotations用法,結(jié)合實(shí)例形式分析了Python3函數(shù)注釋的定義方法與使用技巧,需要的朋友可以參考下2016-07-07PyTorch?TensorFlow機(jī)器學(xué)習(xí)框架選擇實(shí)戰(zhàn)
這篇文章主要為大家介紹了PyTorch?TensorFlow機(jī)器學(xué)習(xí)框架選擇實(shí)戰(zhàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10Python數(shù)據(jù)庫的連接實(shí)現(xiàn)方法與注意事項(xiàng)
這篇文章主要介紹了Python數(shù)據(jù)庫的連接實(shí)現(xiàn)方法與注意事項(xiàng),需要的朋友可以參考下2016-02-02anaconda中安裝的python環(huán)境中沒有pip3的問題及解決
這篇文章主要介紹了anaconda中安裝的python環(huán)境中沒有pip3的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02