python用函數(shù)創(chuàng)造字典的實(shí)例講解
1、使用dict()函數(shù),通過(guò)其他映射(比如其他字典)或者鍵,值對(duì)的序列建立字典。
dict1 = dict(a=’a’, b=’b’, t=’t’) # 傳入關(guān)鍵字print(dict1) dict2 = dict(zip([’one’, ’two’, ’three’], [1, 2, 3])) # 映射函數(shù)方式來(lái)構(gòu)造字典print(dict2) dict3 = dict([(’one’, 1), (’two’, 2), (’three’, 3)]) # 可迭代對(duì)象方式來(lái)構(gòu)造字典print(dict3)
2、使用fromkeys()函數(shù),只用來(lái)創(chuàng)建新字典,不負(fù)責(zé)保存。
當(dāng)通過(guò)一個(gè)字典來(lái)調(diào)用 fromkeys 方法時(shí),如果需要后續(xù)使用一定記得給他復(fù)制給其他的變量。
dict3 = dict.fromkeys([’name’,’age’])print(dict3) dict4 = dict.fromkeys([’name’,’age’],10)print(dict4)
實(shí)例擴(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’]))#實(shí)際運(yùn)行#name:liming#liming’s phone number is 153, address is tianjing.#個(gè)人感覺(jué)書中的代碼寫的比較繁瑣,初學(xué)者看起來(lái)可能會(huì)比較吃力,重新寫了比較簡(jiǎn)單的版本供參考。
到此這篇關(guān)于python用函數(shù)創(chuàng)造字典的實(shí)例講解的文章就介紹到這了,更多相關(guān)python如何用函數(shù)創(chuàng)造字典內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. React+umi+typeScript創(chuàng)建項(xiàng)目的過(guò)程2. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過(guò)程解析3. SharePoint Server 2019新特性介紹4. ASP中常用的22個(gè)FSO文件操作函數(shù)整理5. 三個(gè)不常見(jiàn)的 HTML5 實(shí)用新特性簡(jiǎn)介6. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp7. .Net core 的熱插拔機(jī)制的深入探索及卸載問(wèn)題求救指南8. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)9. 讀大數(shù)據(jù)量的XML文件的讀取問(wèn)題10. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯(cuò)誤頁(yè)的問(wèn)題
