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

    字典(Dictionary)

      键必须不可变,所以可以用数字,字符串或元组充当,列表不行

    字典的遍历

      1、遍历Key

    1 dict1 = {"红球":5,"篮球":3,"黄球":4}
    2 for i in dict1:
    3     print(i)  
      #输出如下
    红球
    篮球
    黄球

       

         (- 如果每个Key同样位数,能将Key每个字符分开。)

    1 dict1 = {"红球":5,"篮球":3,"黄球":4}
    2 for i,b in dict1:
    3     print(i,":“,b)
      #输出如下:
    红 : 球
    篮 : 球
    黄 : 球

      

      2、遍历values

    1 dict1 = {"红球":5,"篮球":3,"黄球":4}
    2 for i in dict1.values():
    3     print(i)
      #输出如下:
    5
    3
    4

      

      3、遍历字典项。【得到tuple类型】

    1 dict1 = {"红球":5,"篮球":3,"黄球":4}
    2 for i in dict1.items():
    3     print(i)
    4 print(type(i))
      输出如下:
    ('红球', 5)
    ('篮球', 3)
    ('黄球', 4)
    <class 'tuple'>

       

         (-遍历字典项的键值。)

    1 dict1 = {"红球":5,"篮球":3,"黄球":4}
    2 for i,b in dict1.items():
    3     print(i,b)
    4 print(type(i))
      #输出如下:
    红球 5
    篮球 3
    黄球 4
    <class 'str'>

    常用增减字典项方法

      增加字典项

        -dict[key] = values

    1 dict1 = {"红球":5,"篮球":3,"黄球":4}
    2 dict1["黑球"] = 6          #方法1 dict[key] = values
    3 print(dict1)
      #输出如下:
    {'红球': 5, '篮球': 3, '黄球': 4, '黑球': 6}

        

        -dict.setdefault(key,values)

    1 dict1 = {"红球":5,"篮球":3,"黄球":4}
    2 dict1.setdefault("黑球",7)        #方法2 dict.setdefault(key,values)
    3 print(dict1) 
      #输出如下:
    {'红球': 5, '篮球': 3, '黄球': 4, '黑球': 7}

       

         -update(关键字=values)、update((key,values))、update({key:values})     

          【以上都可以,输入原有的key时,新values替代旧values】

    1 dict1 = {"红球":5,"篮球":3,"黄球":4}
    2 dict1.update(黑球=7)                 #没有错,黑球并没有双引号!!!!直接传关键字
    3 print(dict1)
      #输出如下:
    {'红球': 5, '篮球': 3, '黄球': 4, '黑球': 7}

      删除字典项

        -pop(key)

    1 dict1 = {"红球":5,"篮球":3,"黄球":4}
    2 dict1.pop("红球")
    3 print(dict1)
      #输出如下:
    {'篮球': 3, '黄球': 4}

        

        -del dict[key] 

    1 dict1 = {"红球":5,"篮球":3,"黄球":4}
    2 del dict1["红球"]            #注意是中括号,不是小括号
    3 print(dict1)
        #输出如下:
    {'篮球': 3, '黄球': 4}
  • 相关阅读:
    xml语言
    java多线程
    MariaDb数据库管理系统的学习(一)安装示意图
    Codeforces Round #274 (Div. 2) --A Expression
    Java常见Exception物种
    JavaIO流程--创建文件和目录的实例
    C#主线程等待子线程运行结束
    向Oracle中插入记录时,出现“Oracle.DataAccess.Client.OracleException ORA-00933 ”错误
    PLSQL Developer报“动态执行表不可访问,本会话的自动统计被禁止”的解决方案
    修改Oracle 表空间名称 tablespace name
  • 原文地址:https://www.cnblogs.com/simplecat/p/11273172.html
Copyright © 2011-2022 走看看