Python--字典基本操作

深藏阁楼爱情的钟 2021-12-21 03:39 449阅读 0赞
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author:Huanglinsheng
  4. # 字典的特性:
  5. # dict是无序的
  6. # key必须是唯一的,so 天生去重
  7. info = {
  8. 'stu1': "TengLan Wu",
  9. 'stu2': "LongZe Luola",
  10. 'stu3': "XiaoZe Maliya",
  11. }
  12. print(info.values())
  13. print(info.keys())
  14. #setdefault
  15. info.setdefault("stu6","Alex")
  16. #增加
  17. info["stu4"] = "hls"
  18. #修改
  19. info["stu4"] = "hc"
  20. #删除
  21. info.pop("stu4")
  22. del info["stu3"]
  23. info.popitem() #随机删除
  24. #查找
  25. # "stu1102" in info #标准用法
  26. # info.get("stu1102") #获取
  27. # info["stu1102"] #同上,但是看下面
  28. # info["stu1105"] #如果一个key不存在,就报错,get不会,不存在只返回None
  29. #update
  30. b = {1:2,3:4, "stu1102":"龙泽萝拉"}
  31. info.update(b)
  32. #items
  33. # info.items()
  34. # dict_items([('stu1102', '龙泽萝拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')])
  35. #循环dict
  36. #方法1
  37. for key in info:
  38. print(key,info[key])
  39. #方法2
  40. for k,v in info.items(): #会先把dict转成list,数据里大时莫用
  41. print(k,v)
  42. #多级字典嵌套及操作
  43. youlan = {
  44. "运维":{
  45. "hc":["帅气","威猛"],
  46. "hls":["菜鸡","挖坑王"]
  47. },
  48. "运营":{
  49. "hht":["靓仔","大佬"],
  50. "lm":["美女","可爱"]
  51. },
  52. "服务端":{
  53. "cyl":["大佬","牛逼"],
  54. "zcw":["美女","可爱"]
  55. }
  56. }
  57. youlan["运维"]["hc"][1] = youlan["运维"]["hc"][1] + "牛逼"
  58. print(youlan["运维"]["hc"][1])
  59. for k in youlan:
  60. print(k)

=======================经典案例==================================

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author:Huanglinsheng
  4. menu = {
  5. '北京':{
  6. '海淀':{
  7. '五道口':{
  8. 'soho':{},
  9. '网易':{},
  10. 'google':{}
  11. }
  12. }
  13. },
  14. '山东':{},
  15. }
  16. exit_flag = False
  17. current_layer = menu
  18. print(menu)
  19. layers = []
  20. while not exit_flag:
  21. for k in current_layer:
  22. print(k)
  23. choice = input(">>:").strip()
  24. if choice == "b":
  25. current_layer = layers[-1]
  26. print(current_layer)
  27. #print("change to laster", current_layer)
  28. layers.pop()
  29. elif choice not in current_layer:continue
  30. else:
  31. layers.append(current_layer)
  32. print(layers)
  33. current_layer = current_layer[choice]
  34. print(current_layer)

转载于:https://www.cnblogs.com/huanglinsheng/p/9361240.html

发表评论

表情:
评论列表 (有 0 条评论,449人围观)

还没有评论,来说两句吧...

相关阅读