zoukankan      html  css  js  c++  java
  • 【python--字典】 dict 创建 的8种方法

    # 字典
    #{}
    dic = {}
    print(dic)
    print(type(dic))   #  <class 'dict'>
    
    # 语法格式  {'xuann':2,'lic':65}
    # key --- 键
    # value --- 值
    # 键值对    一个元素
    
    #  1:创建字典
    d1 = dict()
    print(d1)       #  空字典 {}
    
    #  2:通过直接赋值创建
    di = {'sop':2,'kai':5}
    print(di)      # {'sop': 2, 'kai': 5}
    
    #  3:通过dict函数和关键字创建
    die = dict(snian = 1,ajija = 6,)
    print(die)     #  {'snian': 1, 'ajija': 6}
    
    #  4:通过二元组创建   通过列表转字典
    die =[(15,3),('nijao',3)]
    di = dict(die)
    print(di)      # {15: 3, 'nijao': 3}
    
    #  5:zip函数
    re = zip([1,2,3,6,5,9])     # zip 后 为可迭代对象
    print(re)                     # <zip object at 0x013FF1A8>  迭代器
    for i in re:                  #   迭代循环
        print(i)
        # (1,)
        # (2,)
        # (3,)
        # (6,)
        # (5,)
        # (9,)
    re = zip([1,2,3,4],[11,22,33,44])
    for i in re:
        print(i)
    # (1, 11)
    # (2, 22)
    # (3, 33)
    # (4, 44)
    re = zip('nihao',[1,2,3,4,5,])
    for i in re :
        print(i)
    # ('n', 1)
    # ('i', 2)
    # ('h', 3)
    # ('a', 4)
    # ('o', 5)
    
    # print(re.__next__())          # (1,)
    #   先用zip函数迭代出元组形式的元素  取出  放到字典里
    de = dict(zip('mijao',[1,2,35,4,8]))
    print(de)
    # {'m': 1, 'i': 2, 'j': 35, 'a': 4, 'o': 8}
    
    #  6:通过字典的推导式 创建
    # lis = [i*2 for i in range]     list 推导式
    dic = {str(i) : i*2  for i in range(9)}  #dict 推导式
    print(dic)
    #{'0': 0, '1': 2, '2': 4, '3': 6, '4': 8, '5': 10, '6': 12, '7': 14, '8': 16}
    
    #  7:用 dict.fromkeys
    #通常用来初始化字典,设置value的默认值
    di = dict.fromkeys('nihao',3)          # {k:value,k:value,k:value,........}
    print(di)
    # {'n': 3, 'i': 3, 'h': 3, 'a': 3, 'o': 3}
    
    #  8: 其他方式
    l = ['x',1,'y',2,'o',5]
    de = dict(zip(l[::2],l[1::2]))
    print(de)
    # {'x': 1, 'y': 2, 'o': 5
  • 相关阅读:
    -F, --flush-logs
    perl 处理文本
    zookeeer 集群和伪集群模式
    匿名函数和闭包
    perl 读取cookie
    看医疗行业如何建立信息化战略决策
    浅析职业安全感——北漂18年(63)
    perl 面向对象 new方法
    如何去掉MyEclipse中的MyEclipse Derby
    Not enough space svn: zlib (uncompress): buffer error: Decompression of svndiff data failed
  • 原文地址:https://www.cnblogs.com/lxcai213/p/13298035.html
Copyright © 2011-2022 走看看