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() + '.') ~
結(jié)果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)輸出結(jié)果。
運行結(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)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接
相關文章
VSCode配合pipenv搞定虛擬環(huán)境的實現(xiàn)方法
這篇文章主要介紹了VSCode配合pipenv搞定虛擬環(huán)境的實現(xiàn)方法,文中通過圖文教程介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05python3新特性函數(shù)注釋Function Annotations用法分析
這篇文章主要介紹了python3新特性函數(shù)注釋Function Annotations用法,結(jié)合實例形式分析了Python3函數(shù)注釋的定義方法與使用技巧,需要的朋友可以參考下2016-07-07PyTorch?TensorFlow機器學習框架選擇實戰(zhàn)
這篇文章主要為大家介紹了PyTorch?TensorFlow機器學習框架選擇實戰(zhàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10Python數(shù)據(jù)庫的連接實現(xiàn)方法與注意事項
這篇文章主要介紹了Python數(shù)據(jù)庫的連接實現(xiàn)方法與注意事項,需要的朋友可以參考下2016-02-02anaconda中安裝的python環(huán)境中沒有pip3的問題及解決
這篇文章主要介紹了anaconda中安裝的python環(huán)境中沒有pip3的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02