目標:創建一個字典,記錄幾對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 OrderedDictpython_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 OrderedDictpython_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.
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林站長站的支持。如果你想了解更多相關內容請查看下面相關鏈接
新聞熱點
疑難解答