Python中OrderedDict類如何使用,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。
目標(biāo):創(chuàng)建一個(gè)字典,記錄幾對(duì)python詞語(yǔ),使用OrderedDict類來(lái)寫(xiě),并按順序輸出。
寫(xiě)完報(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寫(xiě)成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)的支持。
網(wǎng)頁(yè)標(biāo)題:Python中OrderedDict類如何使用-創(chuàng)新互聯(lián)
分享URL:http://chinadenli.net/article32/jgjpc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃、移動(dòng)網(wǎng)站建設(shè)、品牌網(wǎng)站制作、服務(wù)器托管、商城網(wǎng)站、電子商務(wù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容