Python中OrderedDict類如何使用,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。
目標(biāo):創(chuàng)建一個(gè)字典,記錄幾對(duì)python詞語(yǔ),使用OrderedDict類來(lái)寫,并按順序輸出。
寫完報(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)簡(jiǎ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.
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。