美文网首页
字典与集合

字典与集合

作者: 拼了老命在学习 | 来源:发表于2020-03-12 19:17 被阅读0次

    字典的创建

    1.直接创建

    dict1 = {1:'one',2:'two',3:'three'}
    print(dict1[1])
    print(dict1)
    

    2.创建空字典

    dict1 = {}
    print(dict1)
    

    3.用工厂函数创建

    • 元组形式创建(可替换为列表形式)
    dict1 = dict(((1,'one'),(2,'two'),(3,'three')))
    print(dict1[1])
    print(dict1)
    
    • key = value进行创建
    dict1 = dict(nike ='one',mike ='two') #用函数创建时key值不能为数值
    print(dict1)
    

    字典的修改

    1.对应key存在时的修改

    dict1 = dict(nike ='one',mike ='two')
    dict1['nike'] = 'just do it'
    print(dict1['nike'])
    

    2.key不存在时,在字典中会添加相应的key

    dict1 = dict(nike ='one',mike ='two')
    dict1['like'] = 'i love you'
    print(dict1)
    

    dict内置函数用法

    1.fromkeys()创建新的字典,并且给不同的key附上相同的值

    dict1 = dict.fromkeys((1,2,3),'kick')
    print(dict1)
    

    2.访问字典的方法:keys()、values()、items()

    #将字典中的key都打印出来
    dict1 = dict.fromkeys(range(10),'kick')
    for eachkey in dict1.keys():
        print(eachkey)
    
    #打印所有value
    dict1 = dict.fromkeys(range(10),'kick')
    for eachvalue in dict1.values():
        print(eachvalue)
    
    #将key和value对应打包
    dict1 = dict.fromkeys(range(10),'kick')
    for eachitem in dict1.items():
        print(eachitem)
    

    3.get(key,value) 当key存在时会访问对应的value值,若key不存在,则会访问get中的value

    dict1 = dict.fromkeys(range(10),'kick')
    print(dict1.get(11,'nihao'))
    print(dict1)
    

    4.清空字典 clear()

    dict1 = dict.fromkeys(range(10),'kick')
    dict1.clear()
    print(dict1)
    

    5.copy()拷贝

    dict1 = dict.fromkeys(range(10),'kick')
    dict2 = dict1.copy() #拷贝对象
    dict3 = dict1 #复制对象
    print(id(dict1),id(dict2),id(dict3)) #拷贝对象和复制对象的ID地址不同,拷贝对象指向另一个地址
    

    6.pop()

    dict1 = dict.fromkeys(range(10),'kick')
    dict2 = dict1.pop(2) #拿走key以及其对应的value
    print(dict2)
    print(dict1)
    

    7.popitem() 随机弹出一项(key,value)

    dict1 = dict.fromkeys(range(10),'kick')
    dict2 = dict1.popitem() 
    print(dict2)
    print(dict1)
    

    8.setdefault() 和get()相似,不同处在于setdefault()在key不存在时,会将key及value填入字典中

    dict1 = dict.fromkeys(range(10),'kick')
    dict2 = dict1.setdefault(11,'苍老师')
    print(dict1[11])
    print(dict1)
    

    9.update()更新字典

    dict1 = dict.fromkeys(range(10),'kick')
    dict2 = {11:"苍老师"}
    dict1.update(dict2)
    print(dict1)
    

    集合,无序,下标不可用

    创建集合

    s1 = {1,2,3,4}
    s2 = set() # 创建空集合
    

    集合的操作

    s1 = set()
    #增加
    s1.add(100)
    s1.update([10,20,30])
    print(s1)
    #删除
    s1.remove(100) #删除指定数据,数据不存在会报错
    s1.discard(100) #删除指定数据,数据不存在不报错
    s1.pop() #随机删除某个数据
    #查找数据
    print(10 in s1) #存在则返回True
    print(10 not in s1) #存在则返回False
    

    相关文章

      网友评论

          本文标题:字典与集合

          本文链接:https://www.haomeiwen.com/subject/cwvpjhtx.html