Python6种创建字典的方式
生活随笔
收集整理的這篇文章主要介紹了
Python6种创建字典的方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.通過關鍵字dict和關鍵字參數創建
>>> dic = dict(spam = 1, egg = 2, bar =3) >>> dic {'bar': 3, 'egg': 2, 'spam': 1}2.通過二元組列表創建
>>> list = [('spam', 1), ('egg', 2), ('bar', 3)] >>> dic = dict(list) >>> dic {'bar': 3, 'egg': 2, 'spam': 1}3.dict和zip結合創建
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' >>> dic = dict(zip('abc', [1, 2, 3])) >>> dic {'a': 1, 'c': 3, 'b': 2}4.通過字典推導式創建
>>> dic = {i:2*i for i in range(3)} >>> dic {0: 0, 1: 2, 2: 4}5.通過dict.fromkeys()創建
通常用來初始化字典, 設置value的默認值
>>> dic = dict.fromkeys(range(3), 'x') >>> dic {0: 'x', 1: 'x', 2: 'x'}6.其他
>>> list = ['x', 1, 'y', 2, 'z', 3] >>> dic = dict(zip(list[::2], list[1::2])) >>> dic {'y': 2, 'x': 1, 'z': 3} 與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Python6种创建字典的方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python创建缩略图和选择轮廓效果
- 下一篇: Python字典列表字段重组形成新的字典