zoukankan      html  css  js  c++  java
  • Python--字典操作

    字典的增删改查及遍历

     1 info = {
     2     "stu3":"yuanyuan",
     3     "stu1":"tianjie",
     4     "stu2":"wangxinlin"
     5 }
     6 print(type(info)) #输出类型
     7 print(info)
     8 print(info["stu1"]) #查找 条件:适用于确定有该键值,没有键值时报错
     9 print(info.get("stu00")) #没有时返回None
    10 print(info.get("stu1")) #有就返回value
    11 
    12 print("stu02" in info) #判断是否存在该数据,如果存在返回True,不存在返回False
    13 # info.has_key("stu1") # 适用于py2
    14 
    15 info["stu2"] = "fenglubei"  #修改
    16 print(info)
    17 info["stu4"] = "wangxinlin" #没有该键时新增
    18 print(info)
    19 
    20 del info["stu1"] #删除
    21 print(info)
    22 
    23 info.pop("stu2") #删除特定键值
    24 print(info)
    25 
    26 info.popitem() #随机删
    27 print(info)
    28 
    29 #字典嵌套
    30 shuqike = {
    31     "gongsi":{
    32         "kaifa":["ma","jiaming","jiao","yuan","yaqiong","zhendong"],
    33         "yunwei":["yecai","majin"]
    34     },
    35     "SJS":{
    36         "kaifa":["cong","jiang"],
    37         "yunwei":["feng","tian","xinlin","yuanyuan"]
    38     }
    39 }
    40 print(shuqike)
    41 
    42 #
    43 print(shuqike["gongsi"]["kaifa"][2])
    44 print(shuqike["SJS"]["yunwei"][2])
    45 
    46 #
    47 shuqike["gongsi"]["kaifa"][2] = "zhen"
    48 print(shuqike)
    49 
    50 #增加
    51 shuqike["gongsi"]["jiagou"] = ["hou","peng"]
    52 print(shuqike)
    53 
    54 #高级
    55 zimu = {
    56     "大写":["A","B","C"],
    57     "小写":["a","b","c"]
    58 }
    59 print(zimu.keys()) #获取列表里的所有key
    60 print(zimu.values()) #获取列表里的所有value
    61 
    62 # setdefault,在字典里取值,当能取到值时就不动字典,当取不到值时,创建一个
    63 zimu.setdefault("qita", [1,2,3])
    64 zimu.setdefault("大写", ["D"])
    65 print(zimu)
    66 
    67 #update,存在交叉,更新值,不存在键则新增
    68 b = {
    69     "小写":"fff",
    70     1:2,
    71     3:4
    72 }
    73 zimu.update(b)
    74 print(zimu)
    75 
    76 print(zimu.items()) #字典转列表
    77 
    78 c = dict.fromkeys([6,7,8],"test") #创建一个字典,key为678,值都为test
    79 print(c)
    80 
    81 d = dict.fromkeys([1,2,3],[1,{"name":"tinajie"},333])
    82 print(d)
    83 d[3][1]["name"] = "yuanyuan"  #都改,并不是只改一个
    84 print(d)
    85 
    86 #字典的遍历
    87 for i in zimu:
    88     print(i) #只打印key
    89     print(i,zimu[i])
    90 
    91 for k,v in zimu.items():  #效率低于上面那种,因为要转成列表
    92     print(k,v)
  • 相关阅读:
    2018-2019-2 20175310 个人项目总结报告
    2018-2019-2 20175310 个人项目报告5--勾股数
    2018-2019-2 20175310 个人项目报告6--四方定理
    2018-2019-2 20175310 个人项目报告7--尼科彻斯定理
    #2019-2020-4 《Java 程序设计》第十周总结
    数据库MySQL(20175229张智敏)
    #实验三 敏捷开发与XP实践---实验报告
    课下必做MyCP
    #2019-2020-4 《Java 程序设计》第九周总结
    #2019-2020-4 《Java 程序设计》第八周总结
  • 原文地址:https://www.cnblogs.com/sunnytomorrow/p/12884940.html
Copyright © 2011-2022 走看看