首页 > 代码库 > python dict
python dict
###字典的基本结构 info = { "k1" : "v1", "k2" : "v2" }
###字典的valus可以是任何值 info = { "k1": 18, "k2": True, "k3": [ 11, [], (), 22, 33, { ‘kk1‘: ‘vv1‘, ‘kk2‘: ‘vv2‘, ‘kk3‘: (11,22), } ], "k4": (11,22,33,44) }
###列表,字典不能作为字典的key info = { #["a"]:3 }
###字典是无序的 info = { "k1": 18, "k2": True, "k3": [ 11, [], (), 22, 33, { ‘kk1‘: ‘vv1‘, ‘kk2‘: ‘vv2‘, ‘kk3‘: (11,22), } ], "k4": (11,22,33,44) } print(info) print(info) print(info)
###索引方式找到指定的元素 info = { "k1": 18, "k2": True, "k3": [ 11, [], (), 22, 33, { ‘kk1‘: ‘vv1‘, ‘kk2‘: ‘vv2‘, ‘kk3‘: (11,22), } ], "k4": (11,22,33,44) } print(info["k1"]) #===>18 print(info["k3"][5]["kk3"][0]) #===>11
###字典支持 del 删除 info = { "k1": 18, "k2": True, "k3": [ 11, [], (), 22, 33, { ‘kk1‘: ‘vv1‘, ‘kk2‘: ‘vv2‘, ‘kk3‘: (11,22), } ], "k4": (11,22,33,44) } del info["k3"][5] #===>{‘k2‘: True, ‘k4‘: (11, 22, 33, 44), ‘k1‘: 18, ‘k3‘: [11, [], (), 22, 33]} print(info)
###字典 for 循环 info = { "k1": 18, "k2": True, "k3": [ 11, [], (), 22, 33, { ‘kk1‘: ‘vv1‘, ‘kk2‘: ‘vv2‘, ‘kk3‘: (11,22), } ], "k4": (11,22,33,44) } #默认遍历key for i in info: print(i) #遍历values for i in info.values(): print(i) #遍历key和values for k,v in info.items(): print(k,v)
#字典常用方法 get/update/keys/values/items
#根据Key获取值,key不存在时,可以指定默认值(None) info = { "k1" : "v1", "k2" : "v2" } v = info.get("k1",) vv = info.get("k111", 222) print(v,vv) #===>v1 222 print(info) #===>{‘k2‘: ‘v2‘, ‘k1‘: ‘v1‘}
#更新 info = { "k1" : "v1", "k2" : "v2" } info.update({"k1":23131, "k3":"v3"}) print(info) #===>{‘k3‘: ‘v3‘, ‘k2‘: ‘v2‘, ‘k1‘: 23131}
python dict
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。