标签:copy div method 列表 对象 efault eth none 切片
# 字典 dict类 ,一个kv称为一个键值对,value可以是任意类型,可以多层嵌套. info = {"k1": "v1", "k2":"v2"} info = { "k1":10, "k2":True, "k3":[ 11, 22, 33, { "kk1":"vv1", "kk2":"vv2" } ], "k4":(11, 22, 33, 44) } print(info) # key的值 # list不可以,tuple可以,为什么? # list允许被修改,tuple不允许被修改 # dict是按照hash表进行保存的,所有的key都会转换成一个hash值,放入一个表中,value原样存放,列表是不支持转换成hash值的. # 字典可以作为字典的key吗?不可以. info = { 1: "one", 2: "two", # True:"true", true直接被忽略 #[11]:"v"不允许 (11, 22):"v" #{"k1":"v1"}:"v1" } print(info) # {1: ‘one‘, 2: ‘two‘, (11, 22): ‘v‘} # 字典是有序的吗?每次运行,显示的结果都不一样.因此,字典无序 info = { "k1":10, "k2":True, "k3":[ 11, 22, 33, { "kk1":"vv1", "kk2":(11,22) } ], "k4":(11, 22, 33, 44), 2:"two" } print(info) # 获取值, 只能通过索引,不能通过切片,因为dict是无序的 print(info["k1"]) # 10 print(info[2]) print(info["k3"][3]["kk2"][0]) # 11 # 删除kv del info["k1"] print(info) del info["k3"][3]["kk1"] print(info) # 循环 for,while不可以 for item in info: print(item) #只输出key for item in info.keys(): print(item) # 和上面的结果一样 for item in info.values(): print(item) # 只输出vlaues for key in info.keys(): print(key, info[key]) # 同时输出key和vlaue for k,v in info.items(): print(k, v) # 同时输出key和vlaue
dict的魔法
# clear # copy 浅拷贝 # fromkeys @staticmethod静态方法, 支持类名直接调用该方法 v = dict.fromkeys(["k1", 123], 123) # 传入可迭代对象.根据序列,创建字典,指定统一的值 print(v) # {123: 123, ‘k1‘: 123} # get 根据key获取值,可以不存在时返回None,还可以指定默认值. dic = {"k1": "v1","k3":"v3"} print(dic.get("k1")) print(dic.get("k2")) # None print(dic.get("k2", 1111)) # 1111 # items # keys # values # pop 删除指定key并返回value的值 dic = {"k1": "v1","k3":"v3"} v = dic.pop("k1") print(dic) # {‘k3‘: ‘v3‘} print(v) # v1 v = dic.pop("k2", 90000) # 90000为key不存在的时候默认返回的值.s dic = {"k1": "v1","k3":"v3"} k, v = dic.popitem() # 随机删 print(dic, k, v) # {‘k1‘: ‘v1‘} k3 v3 # setdefault 设置值 # 但若存在,不设置只获取当前key对应的值 # 若不存在,添加kv dic = {"k1": "v1","k3":"v3"} v = dic.setdefault("k1", "123") print(dic, v) # {‘k1‘: ‘v1‘, ‘k3‘: ‘v3‘} v1 v = dic.setdefault("k4", "v4") print(dic, v) # {‘k3‘: ‘v3‘, ‘k1‘: ‘v1‘, ‘k4‘: ‘v4‘} v4 # update dic = {"k1": "v1","k3":"v3"} dic.update({"k1":"111", "k3": 123}) print(dic, v) # {‘k1‘: ‘111‘, ‘k3‘: 123} dic.update(k1=123, k3=356, k4=1234) # python内部做转换,转换成dict print(dic) # {‘k4‘: 1234, ‘k1‘: 123, ‘k3‘: 356} # keys\values\items\get\update
标签:copy div method 列表 对象 efault eth none 切片
原文地址:https://www.cnblogs.com/Windows-phone/p/9715254.html