1.創(chuàng)建空字典
>>> dic = {}>>> type(dic)<type 'dict'>2.直接賦值創(chuàng)建
>>> dic = {'spam':1, 'egg':2, 'bar':3}>>> dic{'bar': 3, 'egg': 2, 'spam': 1}3.通過(guò)關(guān)鍵字dict和關(guān)鍵字參數(shù)創(chuàng)建
>>> dic = dict(spam = 1, egg = 2, bar =3)>>> dic{'bar': 3, 'egg': 2, 'spam': 1}4.通過(guò)二元組列表創(chuàng)建
>>> list = [('spam', 1), ('egg', 2), ('bar', 3)]>>> dic = dict(list)>>> dic{'bar': 3, 'egg': 2, 'spam': 1}5.dict和zip結(jié)合創(chuàng)建
>>> dic = dict(zip('abc', [1, 2, 3]))>>> dic{'a': 1, 'c': 3, 'b': 2}6.通過(guò)字典推導(dǎo)式創(chuàng)建
>>> dic = {i:2*i for i in range(3)}>>> dic{0: 0, 1: 2, 2: 4}7.通過(guò)dict.fromkeys()創(chuàng)建
通常用來(lái)初始化字典, 設(shè)置value的默認(rèn)值
>>> dic = dict.fromkeys(range(3), 'x')>>> dic{0: 'x', 1: 'x', 2: 'x'}8.其他
>>> list = ['x', 1, 'y', 2, 'z', 3]>>> dic = dict(zip(list[::2], list[1::2]))>>> dic{'y': 2, 'x': 1, 'z': 3}總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)VEVB武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選