字典
#字典
**********字典的结构***************************
#1. dict
info = {“k1”:“v1”,“k2”:“v2”}
#### info = {“k1”:“v1”, # 键值对
“k2”:“v2”
}
###2. 字典的value可以是任何值(各元素之间一定要用,隔开)
info = { "k1":15, "k2":True, "k3":[ 11, 22, 33, { "kk1":'vv1', "kk2":'vv2', } ], "k4":(11,22,1,33) } print(info)
#3列表,字典不能作为字典的 key, value可以嵌套任何值 (.布尔值(true=1,false=0),若key与上面key重复则不显示)
#4.字典是无序的(即不能通过切片方式查找)
#5. 索引方式查找指定元素
info = { "k1":15, "k2":True, "k3":[ 11, 22, 33, { "kk1":'vv1', "kk2":'vv2', } ], "k4":(11,22,1,33) } v = info["k3"][0] print(v)
#6.字典支持del删除
info = { "k1":15, "k2":True, "k3":[ 11, 22, 33, { "kk1":'vv1', "kk2":'vv2', } ], "k4":(11,22,1,33) } del info['k3'][3]['kk2'] print(info)
#7.字典支持for循环
info = { "k1":15, "k2":True, "k3":[ 11, 22, 33, { "kk1":'vv1', "kk2":'vv2', } ], "k4":(11,22,1,33) } for k,v in info.items(): print(k,v)
###############################################################
#1.根据序列,创建字典,并指定统一的值
dic = {"k1":'v1'} v = dict.fromkeys(["k1",123,999],123) print(v)
#2. 根据key获取值,key不存在时,可以指定默认值(111111111)或者none
dic = { "k1":'v1' } v = dic.get('k1',111111111) print(v)
#3. 设置值, key已存在,不设置,获取当前key对应的值
key不存在,设置,获取key对应的值
dic = { "k1":'v1', "k2":'v2' } v = dic.setdefault('k1','123') print(dic,v)
②key不存在
dic = { "k1":'v1', "k2":'v2' } v = dic.setdefault('k1111','123') print(dic,v)
#4.update更新的两种写法
dic = { "k1":'v1', "k2":'v2' } dic.update({'k1':'111111','k3':123}) print(dic)
dic = { "k1":'v1', "k2":'v2' } dic.update(k1=123,k3=345,k5="asdf") print(dic)
keys() values() items() get update 在字典中最常用的