本周目标
- 掌握字典(Dict) 的创建、访问、增删改查和遍历
一、为什么需要字典和集合?
假设你有一个班级的学生名单,你想通过姓名快速查到对应的成绩。如果用列表,你需要遍历整个列表才能找到,效率很低。但如果你有一本“花名册”——输入姓名,直接翻到对应页码,这就快多了。
字典就是这样的“花名册”:它存储的是键值对(Key-Value Pair)——每个“键”(姓名)都对应一个“值”(成绩),查找速度极快。
在AI领域,字典无处不在:
- 模型配置:
{"learning_rate": 0.001, "batch_size": 32, "epochs": 100} - 特征映射:
{"cat": 0, "dog": 1, "bird": 2}(将类别名称转为数字标签) - 统计结果:
{"accuracy": 0.95, "loss": 0.23, "f1_score": 0.94}
而集合则像一个“自动去重器”,专门用来存储不重复的元素。在AI中,我们常用它来:
二、字典(Dict)——键值对的“精准快查手册”
1. 什么是字典?如何创建?
字典用花括号 {} 包裹,里面是 键: 值 的配对,键和值之间用冒号分隔,每对之间用逗号分隔。
# 创建空字典empty_dict = {}# 创建包含数据的字典student = {"name": "张三","age": 20,"score": 95,"is_graduated": False}print(student) # {'name': '张三', 'age': 20, 'score': 95, 'is_graduated': False}print(type(student)) # <class 'dict'>
⚠️ 键的要求:字典的键必须是不可变类型(如字符串、数字、元组),列表不能作为键。值可以是任意类型。
2. 访问字典中的值——通过键查找
最直接的访问方式是用方括号 [] 加上键名:
student = {"name": "张三", "age": 20, "score": 95}print(student["name"]) # 张三print(student["age"]) # 20
更安全的方式:get() 方法
如果键不存在,[] 会报错 KeyError,而 get() 会返回 None(或你指定的默认值),更安全:
student = {"name": "张三", "age": 20}print(student.get("score")) # None(键不存在,不会报错)print(student.get("score", 0)) # 0(键不存在,返回默认值0)print(student.get("name", "未知")) # 张三(键存在,返回实际值)
💡 AI小贴士:在读取配置文件时,get() 方法非常有用。比如从配置字典中读取参数,如果某个参数没设置,就用默认值,程序不会崩溃。
3. 修改字典——增、改、删
(1)添加或修改键值对(同一个操作)
如果键不存在,就添加;如果键已存在,就覆盖:
student = {"name": "张三", "age": 20}student["score"] = 95# 添加新键值对print(student) # {'name': '张三', 'age': 20, 'score': 95}student["age"] = 21# 修改已有的键print(student) # {'name': '张三', 'age': 21, 'score': 95}
(2)update():批量更新或合并
student = {"name": "张三", "age": 20}new_data = {"age": 21, "city": "北京"}student.update(new_data)print(student) # {'name': '张三', 'age': 21, 'city': '北京'}
(3)删除键值对
student = {"name": "张三", "age": 20, "city": "北京"}# pop(键):删除指定键,并返回对应的值removed = student.pop("age")print(removed) # 20print(student) # {'name': '张三', 'city': '北京'}# del:删除指定键del student["city"]print(student) # {'name': '张三'}# clear():清空所有键值对student.clear()print(student) # {}
4. 遍历字典
(1)遍历所有键
config = {"lr": 0.001, "batch": 32, "epochs": 100}for key in config:print(key, "=", config[key])# 输出:# lr = 0.001# batch = 32# epochs = 100
(2)遍历所有键值对(items())
config = {"lr": 0.001, "batch": 32, "epochs": 100}for key, value in config.items():print(f"{key}: {value}")# 输出:# lr: 0.001# batch: 32# epochs: 100
(3)只遍历键或只遍历值
config = {"lr": 0.001, "batch": 32, "epochs": 100}print(list(config.keys())) # ['lr', 'batch', 'epochs']print(list(config.values())) # [0.001, 32, 100]
5. 字典常用方法速查表
| | |
|---|
dict[key] | | d["name"] |
dict.get(key, default) | | d.get("age", 0) |
dict[key] = value | | d["score"] = 95 |
update(d2) | | d.update(d2) |
pop(key) | | d.pop("age") |
keys() | | d.keys() |
values() | | d.values() |
items() | | d.items() |
in | | "name" in d |
6. ⚠️ 常见陷阱:KeyError 和 可变键
# 陷阱1:访问不存在的键d = {"a": 1}# print(d["b"]) # ❌ KeyError: 'b'print(d.get("b")) # ✅ 返回 None# 陷阱2:键必须是不可变类型# d = {[1,2]: "value"} # ❌ TypeError:列表不能作为键d = {(1,2): "value"} # ✅ 元组可以
💡 AI小贴士:在AI中,字典最经典的用法之一就是类别到数字的映射(Label Encoding)。比如将 {"猫": 0, "狗": 1, "鸟": 2} 这样的字典,可以把文本标签转换成模型能处理的数字。
三、集合(Set)——自动去重的“元素收纳盒”
1. 什么是集合?如何创建?
集合用花括号 {} 包裹,但它里面只有不重复的、无序的元素。你不能通过索引访问集合中的元素(因为无序)。
# 创建集合fruits = {'苹果', '香蕉', '橙子', '苹果'} # 重复的"苹果"会自动去掉print(fruits) # {'橙子', '香蕉', '苹果'}(无序,顺序可能每次不同)# 从列表创建集合(去重)nums = [1, 2, 2, 3, 3, 3, 4]unique_nums = set(nums)print(unique_nums) # {1, 2, 3, 4}# 创建空集合(注意:{} 是空字典,不是空集合!)empty_set = set() # ✅ 空集合empty_dict = {} # ❌ 这是空字典print(type(empty_set)) # <class 'set'>print(type(empty_dict))# <class 'dict'>
2. 集合的修改——增删
fruits = {'苹果', '香蕉', '橙子'}# 添加元素fruits.add('芒果')print(fruits) # {'芒果', '橙子', '苹果', '香蕉'}# 删除元素(如果元素不存在,会报错)fruits.remove('苹果')print(fruits) # '芒果', '橙子', '香蕉'}# s.remove('草莓') # ❌ KeyError# 安全删除(不存在也不报错)fruits.discard('草莓') # 什么都不发生,也不报错# 随机删除并返回一个元素removed = fruits.pop()print(removed) # 随机删除了一个,不确定是哪个
3. 集合运算——交、并、差
集合支持数学上的集合运算,非常高效:
A = {1, 2, 3, 4}B = {3, 4, 5, 6}# 并集(所有元素)print(A | B) # {1, 2, 3, 4, 5, 6}print(A.union(B)) # 同上# 交集(共同元素)print(A & B) # {3, 4}print(A.intersection(B)) # 同上# 差集(在A中但不在B中)print(A - B) # {1, 2}print(A.difference(B)) # 同上# 对称差集(不同时在A和B中的元素)print(A ^ B) # {1, 2, 5, 6}print(A.symmetric_difference(B)) # 同上
💡 AI小贴士:集合运算在数据分析中很实用。比如你有网站A的访客集合和网站B的访客集合,可以快速计算“同时访问两个网站的用户”(交集)、“只访问A的用户”(差集)等。
4. 集合推导式(类似列表推导式)
# 快速生成一个集合(自动去重)squares = {x**2for x inrange(-3, 4)}print(squares) # {0, 1, 4, 9}(-3和3的平方都是9,自动去重)
四、字典与集合的对比总结
五、实战项目:单词词频统计器
在AI的自然语言处理(NLP) 中,统计单词出现频率是最基础的操作之一。比如分析一篇文章的关键词、构建词袋模型(Bag-of-Words)等。本周我们就来实现一个“单词词频统计器”。
功能需求
完整代码
# =============================================# 单词词频统计器# 知识点:字符串处理 + 字典 + 集合 + 排序# =============================================defclean_text(text):""" 清洗文本:转为小写,移除标点符号,按空格分词 """# 定义标点符号集合(用集合便于快速判断) punctuations = {'.', ',', '!', '?', ';', ':', '"', "'", '(', ')', '-', '_', '\n', '\t'}# 转为小写 text = text.lower()# 替换标点符号为空格(这样标点不会粘在单词上)for p in punctuations: text = text.replace(p, ' ')# 按空白字符分割成单词列表(多个空格会自动处理) words = text.split()return wordsdefcount_word_frequency(words):""" 统计词频:返回字典 {单词: 次数} """ freq = {}for word in words:# 如果单词已存在,次数+1;否则初始化为1if word in freq: freq[word] += 1else: freq[word] = 1return freqdefsort_by_frequency(freq_dict):""" 按词频从高到低排序,返回排序后的列表(元组列表) """# sorted() 可以按字典的值排序,reverse=True 表示降序# freq_dict.items() 返回 (单词, 次数) 对# key=lambda item: item[1] 表示按次数(第2个元素)排序 sorted_items = sorted(freq_dict.items(), key=lambda item: item[1], reverse=True)return sorted_itemsdefprint_report(sorted_items, total_words):""" 打印统计报告 """print("\n" + "=" * 40)print(" 📊 词频统计报告")print("=" * 40)print(f"总单词数(含重复):{total_words}")print(f"不同单词数:{len(sorted_items)}")print("-" * 40)print("排名\t单词\t\t次数")print("-" * 40)# 只显示前20个高频词(如果太多) top_n = min(20, len(sorted_items))for i, (word, count) inenumerate(sorted_items[:top_n], start=1):# 排版对齐:单词长度小于8时加制表符iflen(word) < 8:print(f"{i}\t{word}\t\t{count}")else:print(f"{i}\t{word}\t{count}")iflen(sorted_items) > 20:print(f"... 还有 {len(sorted_items) - 20} 个单词未显示")print("=" * 40)# ========== 主程序入口 ==========print("👋 欢迎使用单词词频统计器!")print("请输入一段英文文本(输入空行结束):")# 读取多行文本(用户输入空行表示结束)lines = []whileTrue: line = input()if line == "":break lines.append(line)# 合并所有行full_text = " ".join(lines)# 检查是否有输入ifnot full_text.strip():print("⚠️ 您没有输入任何文本,程序退出。")else:# 清洗文本 words = clean_text(full_text)# 统计词频 freq = count_word_frequency(words)# 排序 sorted_words = sort_by_frequency(freq)# 打印报告 print_report(sorted_words, len(words))
运行效果示例
👋 欢迎使用单词词频统计器!请输入一段英文文本(输入空行结束):The quick brown fox jumps over the lazy dog. The dog sleeps, and the fox runs away.(空行)======================================== 📊 词频统计报告========================================总单词数(含重复):17不同单词数:12----------------------------------------排名 单词 次数----------------------------------------1 the 42 dog 23 fox 24 quick 15 brown 16 jumps 17 over 18 lazy 19 sleeps 110 and 111 runs 112 away 1========================================
六、动手练习
练习1:字典基础操作
创建字典 person = {"name": "李四", "age": 28, "city": "上海"},完成:
- 安全地获取
"salary" 键的值,如果不存在返回 "未知"
👆 点击查看参考答案person = {"name": "李四", "age": 28, "city": "上海"}person["job"] = "工程师"person["age"] = 29salary = person.get("salary", "未知")print(salary) # 未知del person["city"]for key, value in person.items():print(f"{key}: {value}")# 输出:# name: 李四# age: 29# job: 工程师
练习2:集合去重与运算
给定两个列表 A = [1, 2, 3, 4, 5] 和 B = [4, 5, 6, 7, 8]:
👆 点击查看参考答案A = [1, 2, 3, 4, 5]B = [4, 5, 6, 7, 8]setA = set(A)setB = set(B)print(setA & setB) # {4, 5}print(setA - setB) # {1, 2, 3}print(setA | setB) # {1, 2, 3, 4, 5, 6, 7, 8}
练习3:统计字符串中字符出现次数
给定字符串 s = "abracadabra",统计每个字符出现的次数,输出字典形式(如 {"a": 5, "b": 2, ...})。
👆 点击查看参考答案s = "abracadabra"char_count = {}for ch in s: char_count[ch] = char_count.get(ch, 0) + 1print(char_count) # {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
练习4:学生成绩字典排序
有一个字典 scores = {"张三": 85, "李四": 92, "王五": 78, "赵六": 90},请按成绩从高到低输出学生姓名和成绩。
👆 点击查看参考答案scores = {"张三": 85, "李四": 92, "王五": 78, "赵六": 90}sorted_items = sorted(scores.items(), key=lambda item: item[1], reverse=True)for name, score in sorted_items:print(f"{name}: {score}")# 李四: 92# 赵六: 90# 张三: 85# 王五: 78# sorted python内置函数,第一个参数可迭代对象,key:用来比较的元素,reverse:默认False(升序),True(降序)
练习5(AI场景模拟):类别映射与反转
在分类任务中,我们常需要类别名称和数字标签之间的双向映射。现有类别标签 ["猫", "狗", "鸟", "猫", "鸟", "狗", "狗"]:
- 创建一个字典
label_to_id,为每个不同类别分配一个唯一的整数 ID(从0开始) - 创建反向字典
id_to_label(键为ID,值为类别名) - 验证:将 ID 列表转换回类别标签,应与原始列表一致
👆 点击查看参考答案labels = ["猫", "狗", "鸟", "猫", "鸟", "狗", "狗"]# 1. 自动分配IDunique_labels = list(set(labels)) # 去重unique_labels.sort() # 排序使结果可复现label_to_id = {label: idx for idx, label inenumerate(unique_labels)}print(label_to_id) # {'鸟': 0, '狗': 1, '猫': 2}# 2. 转换为IDids = [label_to_id[label] for label in labels]print(ids) # [2, 1, 0, 2, 0, 1, 1]# 3. 反向字典id_to_label = {id_: label for label, id_ in label_to_id.items()}print(id_to_label) # {0: '鸟', 1: '狗', 2: '猫'}# 4. 验证转换回来recovered = [id_to_label[id_] for id_ in ids]print(recovered) # ['猫', '狗', '鸟', '猫', '鸟', '狗', '狗']assert recovered == labelsprint("✅ 验证通过!")
本周小结
本周我们学习了另外两种重要的数据容器:
| |
|---|
| 字典(Dict) | {key: value} |
| 字典增删改 | 直接赋值添加/修改,pop() 删除,update() 合并 |
| 安全访问 | get(key, default) |
| 遍历字典 | items() 同时获取键和值,keys()、values() 单独获取 |
| 集合(Set) | |
| 集合运算 | | |
| 实战应用 | |
下周预告:我们将学习**函数(Function)**的完整知识——包括函数的定义与调用、参数传递、返回值、作用域、以及lambda表达式和装饰器的入门。函数是模块化编程的核心,掌握它之后,你就能把代码组织得井井有条。
📌 本周作业建议:
- 运行“单词词频统计器”,找一段英文文章(比如新闻)测试效果,观察高频词有哪些。
- 修改词频统计器,让它能忽略常见的停用词(如 "the", "a", "an", "of" 等),只统计有意义的实词。
- 在实际的AI项目中,字典用于保存模型训练过程中的各种指标。试试用字典保存一个“训练日志”:每轮训练记录
{"epoch": 1, "loss": 0.5, "acc": 0.8},并存储在一个列表中。
字典和集合在AI开发中使用频率极高,好好掌握它们,会让你的代码更高效、更优雅! 🚀