跳至正文
View Categories

< 1 min read

主要内容 #

  • 字典常用内置函数的使用: keys()、values()、items()、get()、update()
  • 1. keys() #

    字典内置函数keys()可获取字典所有的键值,返回的结果为一个迭代器(迭代器属于可迭代对象的一种) 可通过list()函数将迭代器转换成一个列表,方便显示具体的内容,例如:
    dict1 = {"name": "小明", "birth": "2005/06", "code": 1}
    iter = dict1.keys()
    print(iter)   #打印迭代器
    
    list1 = list(iter)  #将迭代器转换成列表
    print(list1)

    2. values() #

    字典内置函数values()可获取字典所有的,返回的结果为一个迭代器(迭代器属于可迭代对象的一种) 可通过list()函数将迭代器转换成一个列表,方便显示具体的内容,例如:
    dict1 = {"name": "小明", "birth": "2005/06", "code": 1}
    iter = dict1.values()
    print(iter)   #打印迭代器
    
    list1 = list(iter)  #将迭代器转换成列表
    print(list1)

    3. items() #

    字典内置函数items()可获取字典所有的键值对,返回的结果为一个迭代器(迭代器属于可迭代对象的一种) 可通过list()函数将迭代器转换成一个列表,方便显示具体的内容,例如: 转换成的列表中,每一个元素为一个元组,元组的第一个元素为键值,第二个元素为值
    dict1 = {"name": "小明", "birth": "2005/06", "code": 1}
    iter = dict1.items()
    print(iter)   #打印迭代器
    
    list1 = list(iter)  #将迭代器转换成列表
    print(list1)

    4. get() #

    字典内置函数get(key,default)可获取指定键值key所对应的值value。 当指定的键值key不在字典中时,返回default所设置的值,比如:
    dict1 = {"name": "小明", "birth": "2005/06", "数学": 95}
    math = dict1.get("数学", 0)   #根据键值"数字"获取对应的值
    print(math)
    
    English = dict1.get("英语", 0)  #根据键值"英语"获取对应的值,如果该键值不在字典中,则返回0
    print(English)

    5. update() #

    字典内置函数update()可将一个字典添加到另一个字典中,格式如下: dict1.update(dict2) 功能:将字典dict2的键值对添加到字典dict1中,比如:
    dict1 = {"name": "小明", "birth": "2005/06", "code": 1}
    dict2 = {"语文": 95, "数学": 100, "英语": 98}
    dict1.update(dict2)
    print(dict1)

    6. 小结 #

  • 字典常用内置函数的使用: keys()、values()、items()、get()、update()
  • OJ训练题 #

    1、练21.3 神奇装置 – ★
    2、【入门】请输出1~n之间所有的整数 – ★
    3、【入门】分配任务 – ★
    4、【入门】至少要买几瓶止咳糖浆? – ★★
    5、【例34.3】 统计数字字符个数 – ★★★