python 基础系列07-字典集合

#python 基础系列07-字典集合

#引入sys库
import sys
import copy

if __name__ == '__main__':
    a,b,c =1,2,3

    #字段的访问效率速度要优于集合跟元组,字典是无序的,是可变的
    mydict = {1:'a111',2:'bccc'}
    print(type(mydict))
    print(mydict[1],mydict[2])

    #创建字典 方式一
    dict1 = dict((['1','2'],['aa','bb']))
    print(dict1) #{1: 2, 'aa': 'bb'}

    # 创建字典 方式二
    dict2 = dict.fromkeys([1,2,3,4],'xxxx')
    dict3 = dict.fromkeys('abcd','xxxx')
    print(dict2)#{1: 'xxxx', 2: 'xxxx', 3: 'xxxx', 4: 'xxxx'}
    print(dict3) #{'a': 'xxxx', 'b': 'xxxx', 'c': 'xxxx', 'd': 'xxxx'}

    #字典获取参数值
    print(dict1.keys()) #dict_keys([1, 'aa'])
    print(dict1.values()) #dict_values([2, 'bb'])
    print(dict1['1'],dict1['aa'])
    #循环
    for var in dict1:
        print(var)
    #判断key是否存在 ,不能判断value值
    print('1' in dict1)

    #删除值
    del  mydict[1]
    print(mydict)

    #pop 函数删除值 并保持值
    rs  = mydict.pop(2)
    print(mydict) # {}
    print(rs) #bccc

    #清空字典
    mydict.clear()


    #集合set 分为可变跟不可变集合 ,集合是去重的类似set,集合是乱序的

    myset = {'a','b','c','d','d'}
    myset2 = set([1,2,3,4])
    print(myset)

    #创建不可变集合
    myset_no = frozenset([1,2,34,5,6])

    #循环访问值
    for  i in myset:
        print(i)

    #更新集合 #不可变集合不能更新
    myset.add(('1','2'))
    print(myset)
    myset.update(('112aa','hhhh')) #{'b', '112aa', 'hhhh', ('1', '2'), 'a', 'c', 'd'}
    print(myset)
    #判断是否在
    print('a' in  myset)
    #删除集合
    #myset.remove()
    #del myset

    #判断交集和子集
    myset < myset #前者是否是后者的子集
    myset > myset #前者是否是后者的超集

    #集合跟集合联合 交集 差补 对称差分
    myset | myset
    myset & myset
    myset - myset
    myset ^ myset

猜你喜欢

转载自blog.csdn.net/qq_31866793/article/details/104352273