课件编号17704169

17、Python 字典(Dictionary)(教案)

日期:2024-06-01 科目:信息技术 类型:初中教案 查看:84次 大小:20992Byte 来源:二一课件通
预览图 1/1
Python,字典,Dictionary,教案
  • cover
Python 字典(Dictionary)(教案) 教学目标: 1、理解 Python 字典的基本概念和特点 2、掌握字典的创建、访问和修改等操作 3、熟悉字典的常见用法和应用场景 重点: 1、字典的创建和基本操作 2、字典的键和值的类型 3、字典的常见用法和应用场景 难点: 字典的遍历和操作技巧 教学准备: 1、一台安装有 Python 的电脑 2、Python 编辑器(推荐使用 PyCharm、Jupyter Notebook 等) 3、教学用的代码示例 教学过程: 1. 引入字典的概念和作用,解释字典与列表的区别。 # 代码示例:字典与列表的区别 fruits_list = ["apple", "banana", "orange"] print(fruits_list[0]) # 输出:apple fruits_dict = {"name": "apple", "color": "red", "price": 1.5} print(fruits_dict["name"]) # 输出:apple 2. 介绍字典的创建和访问: (1)、使用大括号 `{}` 或 `dict()` 创建一个空字典 (2)、使用键值对来创建字典,键和值之间使用冒号 `:` 分隔 (3)、使用方括号 `[]` 或 `get()` 方法访问字典中的值 # 代码示例:字典的创建和访问 empty_dict = {} print(empty_dict) # 输出:{} fruits = {"name": "apple", "color": "red", "price": 1.5} print(fruits["name"]) # 输出:apple print(fruits.get("color")) # 输出:red 3. 对比列表和字典的访问方式: (1)列表通过下标索引访问元素 (2)字典通过键访问值(支持字符串、数值、元组等类型作为键) # 代码示例:列表和字典的访问方式对比 fruits_list = ["apple", "banana", "orange"] print(fruits_list[0]) # 输出:apple fruits_dict = {"name": "apple", "color": "red", "price": 1.5} print(fruits_dict["name"]) # 输出:apple 4. 演示字典的修改和删除操作: (1)直接通过键来修改和添加字典中的值 (2)使用 `del` 关键字删除字典中的元素 # 代码示例:字典的修改和删除操作 fruits = {"name": "apple", "color": "red", "price": 1.5} fruits["price"] = 2.0 fruits["quantity"] = 10 print(fruits) # 输出:{"name": "apple", "color": "red", "price": 2.0, "quantity": 10} del fruits["color"] print(fruits) # 输出:{"name": "apple", "price": 2.0, "quantity": 10} 5. 介绍字典的常见用法和应用场景: (1)存储和处理具有键-值对关系的数据 (2)统计词频、记录学生信息、建立联系人等 # 代码示例:字典的常见用法 words = {"apple": 3, "banana": 2, "orange": 1} print(words["apple"]) # 输出:3 student = {"name": "Alice", "age": 18, "grade": "A"} print(student) # 输出:{"name": "Alice", "age": 18, "grade": "A"} contacts = { "Alice": "alice@", "Bob": "bob@", "Charlie": "charlie@" } print(contacts["Alice"]) # 输出:alice@ 6. 演示字典的遍历和操作技巧: (1)使用 `for` 循环遍历字典的键和值 (2)使用字典的方法如 `keys()`、`values()`、`items()` 等进行操作 # 代码示例:字典的遍历和操作技巧 fruits = {"name": "apple", "color": "red", "price": 1.5} for key in fruits: print(key, fruits[key]) print(fruits.keys()) # 输出:dict_keys(["name", "color", "price"]) print(fruits.values()) # 输出:dict_values(["apple", "red", 1.5]) print(fruits.items()) # 输出:dict_items([("name", "apple"), ("color", "red"), ("price", 1.5)]) 课堂练习: 1. 创建一个字典,包含学生的姓名和年龄。使用键访问各个学生的年龄并打印出来。 2. 创建一个字典,包含水果的名称和价格。使用循环遍历字典,计算水果的总价格并打印出来。 3. 创建一个空字典,使用循环输入学生的姓名和成绩,并将其存储在字典中。最后打印学生信息。 ... ...

~~ 您好,已阅读到文档的结尾了 ~~