python實(shí)現(xiàn)在無須過多援引的情況下創(chuàng)建字典的方法
本文實(shí)例講述了python實(shí)現(xiàn)在無須過多援引的情況下創(chuàng)建字典的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
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.加參數(shù)
dict = dict(red = 1,bule = 2,yellow = 3) print dict
結(jié)果為:{'yellow': 3, 'bule': 2, 'red': 1}
3.使用內(nèi)置的zip函數(shù)
zip([iterable,...])返回一個(gè)列表,
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
結(jié)果:
<type 'list'>
{33: '22222222222', 'ab': 'aaaa', '22': 'dddddddd'}
4.dict的fromkeys函數(shù)
創(chuàng)建的每個(gè)鍵有相同的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
結(jié)果:{33: 0, 'ab': 0, '22': 0}
import string count_by_letter = dict.fromkeys(string.ascii_lowercase,0) print count_by_letter
結(jié)果:
{'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}
希望本文所述對(duì)大家Python程序設(shè)計(jì)的學(xué)習(xí)有所幫助。
相關(guān)文章
一篇文章教你用Python實(shí)現(xiàn)一鍵文件重命名
這篇文章主要介紹了如何用python一鍵文件重命名,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
TensorFlow安裝及jupyter notebook配置方法
下面小編就為大家?guī)硪黄猅ensorFlow安裝及jupyter notebook配置方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09
淺談Python實(shí)現(xiàn)2種文件復(fù)制的方法
這篇文章主要介紹了淺談Python實(shí)現(xiàn)2種文件復(fù)制的方法,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
詳談python中subprocess shell=False與shell=True的區(qū)別
這篇文章主要介紹了詳談python中subprocess shell=False與shell=True的區(qū)別說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04

