Python中OrderedDict類如何使用,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

目標:創建一個字典,記錄幾對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循環的for寫成from了……總是出現簡單的錯誤。
最終,正確代碼如下:
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類;
第二行,創建了OrderedDict類的一個實例,并將其存儲到python_terms中,也就是創建了一個空字典;
第三至五行,為字典添加鍵值對;
最后,循環輸出結果。
運行結果:
[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.
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創新互聯行業資訊頻道,感謝您對創新互聯的支持。
                網頁標題:Python中OrderedDict類如何使用-創新互聯
                
                分享URL:http://www.yijiale78.com/article32/jgjpc.html
            
成都網站建設公司_創新互聯,為您提供網站策劃、移動網站建設、品牌網站制作、服務器托管、商城網站、電子商務
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯
