python用函數(shù)創(chuàng)造字典的實例講解
1、使用dict()函數(shù),通過其他映射(比如其他字典)或者鍵,值對的序列建立字典。
dict1 = dict(a=’a’, b=’b’, t=’t’) # 傳入關(guān)鍵字print(dict1) dict2 = dict(zip([’one’, ’two’, ’three’], [1, 2, 3])) # 映射函數(shù)方式來構(gòu)造字典print(dict2) dict3 = dict([(’one’, 1), (’two’, 2), (’three’, 3)]) # 可迭代對象方式來構(gòu)造字典print(dict3)
2、使用fromkeys()函數(shù),只用來創(chuàng)建新字典,不負(fù)責(zé)保存。
當(dāng)通過一個字典來調(diào)用 fromkeys 方法時,如果需要后續(xù)使用一定記得給他復(fù)制給其他的變量。
dict3 = dict.fromkeys([’name’,’age’])print(dict3) dict4 = dict.fromkeys([’name’,’age’],10)print(dict4)
實例擴(kuò)展:
代碼:字典示例
people = { ’libai’:{’phone’:’189’,’addr’:’jiangxi’},’lilei’:{’phone’:’180’,’adder’:’hunan’}, ’lihong’:{’phone’:’152’,’adder’:’hubei’},’liming’:{’phone’:’153’,’adder’:’tianjing’}, ’licheng’:{’phone’:’154’,’adder’:’beijing’}}name = input(’name:’)if name in people: print('{}’s phone number is {}, address is {}.'.format(name,people[name][’phone’],people[name][’adder’]))#實際運(yùn)行#name:liming#liming’s phone number is 153, address is tianjing.#個人感覺書中的代碼寫的比較繁瑣,初學(xué)者看起來可能會比較吃力,重新寫了比較簡單的版本供參考。
到此這篇關(guān)于python用函數(shù)創(chuàng)造字典的實例講解的文章就介紹到這了,更多相關(guān)python如何用函數(shù)創(chuàng)造字典內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 以PHP代碼為實例詳解RabbitMQ消息隊列中間件的6種模式2. Python如何進(jìn)行時間處理3. python web框架的總結(jié)4. 詳解Python模塊化編程與裝飾器5. Python通過format函數(shù)格式化顯示值6. html小技巧之td,div標(biāo)簽里內(nèi)容不換行7. python裝飾器三種裝飾模式的簡單分析8. Python 如何將integer轉(zhuǎn)化為羅馬數(shù)(3999以內(nèi))9. Python實現(xiàn)迪杰斯特拉算法過程解析10. python使用ctypes庫調(diào)用DLL動態(tài)鏈接庫
