#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Huanglinsheng # 字典的特性: # dict是无序的 # key必须是唯一的,so 天生去重 info = { 'stu1': "TengLan Wu", 'stu2': "LongZe Luola", 'stu3': "XiaoZe Maliya", } print(info.values()) print(info.keys()) #setdefault info.setdefault("stu6","Alex") #增加 info["stu4"] = "hls" #修改 info["stu4"] = "hc" #删除 info.pop("stu4") del info["stu3"] info.popitem() #随机删除 #查找 # "stu1102" in info #标准用法 # info.get("stu1102") #获取 # info["stu1102"] #同上,但是看下面 # info["stu1105"] #如果一个key不存在,就报错,get不会,不存在只返回None #update b = {1:2,3:4, "stu1102":"龙泽萝拉"} info.update(b) #items # info.items() # dict_items([('stu1102', '龙泽萝拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')]) #循环dict #方法1 for key in info: print(key,info[key]) #方法2 for k,v in info.items(): #会先把dict转成list,数据里大时莫用 print(k,v) #多级字典嵌套及操作 youlan = { "运维":{ "hc":["帅气","威猛"], "hls":["菜鸡","挖坑王"] }, "运营":{ "hht":["靓仔","大佬"], "lm":["美女","可爱"] }, "服务端":{ "cyl":["大佬","牛逼"], "zcw":["美女","可爱"] } } youlan["运维"]["hc"][1] = youlan["运维"]["hc"][1] + "牛逼" print(youlan["运维"]["hc"][1]) for k in youlan: print(k)
=======================经典案例==================================
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Huanglinsheng menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, 'google':{} } } }, '山东':{}, } exit_flag = False current_layer = menu print(menu) layers = [] while not exit_flag: for k in current_layer: print(k) choice = input(">>:").strip() if choice == "b": current_layer = layers[-1] print(current_layer) #print("change to laster", current_layer) layers.pop() elif choice not in current_layer:continue else: layers.append(current_layer) print(layers) current_layer = current_layer[choice] print(current_layer)