0Pricing
Python For Kids · 课时

字典

使用键值对存储数据。

字典 是 CoddyKit 上的免费 Python For Kids 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python For Kids 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python For Kids 课程共包含 4 节课。

字典简介

字典

欢迎学习数据结构课程!今天,我们将学习 Python 中的字典,它可以让您以键值对的形式存储数据。

字典 — 插图 1

什么是字典?

字典是由多个项目组成的集合,每个项目都以键和值的形式存储。字典适合组织数据,您可以根据唯一的键轻松检索信息。

  • 键:每个项目的唯一标识符。
  • 值:与键关联的数据。

创建字典

创建字典时,可以将项目放在花括号({})内,并用逗号分隔。每个键和值之间用冒号(:)分隔。

示例:

# Creates a dictionary of student grades
grades = {
    "Alice": 85,
    "Bob": 92,
    "Charlie": 78
}

访问字典值

您可以将特定键放在方括号([])内,或使用 get() 方法,访问与该键关联的值。

示例:

# Accesses the grade of Alice using square brackets
print(grades["Alice"])  # Output: 85

# Accesses the grade of Bob using the get() method
print(grades.get("Bob"))  # Output: 92

向字典添加项目

您可以为新键赋值,向字典添加新的键值对。

示例:

# Adds a new student to the grades dictionary
grades["Diana"] = 88

# Prints the updated dictionary
print(grades)  # Output: {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Diana': 88}

修改字典值

由于字典是可变的,因此您可以更改与现有键关联的值。

示例:

# Updates Charlie's grade
grades["Charlie"] = 82

# Prints the updated grade for Charlie
print(grades["Charlie"])  # Output: 82

从字典中删除项目

您可以使用 del 语句或 pop() 方法从字典中删除项目。

示例:

# Removes Bob from the grades dictionary using del
del grades["Bob"]

# Removes Diana from the grades dictionary using pop()
grades.pop("Diana")

# Prints the updated dictionary
print(grades)  # Output: {'Alice': 85, 'Charlie': 82}

遍历字典

您可以使用 for 循环遍历字典,以访问其中的键和值。

示例:

# Iterates through the dictionary and prints keys and values
for student, grade in grades.items():
    print(student + " scored " + str(grade))
    
# Output:
# Alice scored 85
# Charlie scored 82
# Creates a dictionary of fruits and their colors
fruits = {
    "apple": "red",
    "banana": "yellow",
    "grape": "purple"
}

# Updates the color of banana
fruits["banana"] = "green"

# Removes grape from the dictionary
del fruits["grape"]

# Prints the dictionary
print(fruits)

做得很好!

您已经学会了如何使用字典以键值对的形式存储和管理数据。字典是 Python 程序中用于整理信息的强大工具。请继续练习:创建您自己的字典,并尝试使用它们的各种功能!

字典 — 插图 10

常见问题解答

「字典」课时是免费的吗?

是的 — 「字典」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python For Kids 课程的其余内容,请升级到 CoddyKit PRO。 Python For Kids 课程共包含 4 节课。

「字典」这节课中我会学到什么?

使用键值对存储数据。 你通过在浏览器中直接运行的动手代码来练习 Python For Kids,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Python For Kids 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Python For Kids 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「字典」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Python For Kids 课中编写并运行代码吗?

能。每节 Python For Kids 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 列表与元组
  2. 字典
  3. 集合
  4. 操作数据结构
← 返回 Python For Kids