本文實例講述了python實現在無須過多援引的情況下創建字典的方法。分享給大家供大家參考。具體實現方法如下:
1.使用itertools模塊
import itertools the_key = ['ab','22',33] the_vale = ['aaaa',"dddddddd",'22222222222'] d = dict(itertools.izip(the_key,the_vale)) print d
2.加參數
dict = dict(red = 1,bule = 2,yellow = 3) print dict
結果為:{'yellow': 3, 'bule': 2, 'red': 1}
3.使用內置的zip函數
zip([iterable,...])返回一個列表,
the_key = ['ab','22',33] the_vale = ['aaaa',"dddddddd",'22222222222'] dict2 = dict(zip(the_key,the_vale)) print type(zip(the_key,the_vale)) print dict2
結果:
{33: '22222222222', 'ab': 'aaaa', '22': 'dddddddd'}
4.dict的fromkeys函數
創建的每個鍵有相同的value
fromkeys(seq[,value]) Create a new dictionary with keys from seq and values set to value. the_key = ['ab','22',33] the_vale = 0 d = dict.fromkeys(the_key,the_vale) print
結果:{33: 0, 'ab': 0, '22': 0}
import string count_by_letter = dict.fromkeys(string.ascii_lowercase,0) print count_by_letter
結果:
{'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, 'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}
希望本文所述對大家Python程序設計的學習有所幫助。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
