Python
基础语法
01概念
02安装
03变量
04字符串
05数
06常量与注释
07列表
08元组
09if语句
10字典
11集合
12复合数据类型对比
13推导式
14用户输入
15while循环
16函数
17类
18面向对象编程
19文件操作
20异常处理
21日期和时间
22魔术方法
23内置函数
24线程
25并发&并行
26正则表达式
27迭代器
28装饰器
29生成器
30上下文管理器
31函数式编程
32闭包
33解包
34工具库
35连接关系型数据库
36虚拟环境
37异步编程
网络爬虫
01urllib库[了解]
02requests库
03数据交换格式
04解析库
05lxml
06Beautiful Soup
07Xpath语法
08动态网页的处理
-
+
首页
10字典
## 概念 字典(dict)由一系列**键值对**组成,每个 “键” 对应一个 “值”,键和值之间用冒号:连接,键值对之间用逗号,分隔,整体用花括号{}包裹。 例如: - 存储一个人的信息:{"name": "张三", "age": 30, "city": "北京"} - 存储学生成绩:{"数学": 90, "语文": 85, "英语": 95} ## 创建 **直接使用{}创建** ```python >>> person = { ... "name": "张三", # 键"name"对应值"张三" ... "age": 30, # 键"age"对应值30 ... "is_student": False # 键"is_student"对应值False ... } >>> print(person) {'name': '张三', 'age': 30, 'is_student': False} ``` ```python >>> mixed_dict = { ... 1: "数字键", # 整数作为键 ... ("a", "b"): [1, 2], # 元组作为键(元组是不可变类型) ... "list": [1, 2, 3] # 列表作为值 ... } >>> print(mixed_dict) {1: '数字键', ('a', 'b'): [1, 2], 'list': [1, 2, 3]} ``` **dict()函数创建** dict()函数可通过 “键值对参数” 或 “可迭代对象” 创建字典: ```python # 方式1:通过键值对参数(key=value形式) >>> person = dict(name="张三", age=30, city="北京") >>> print(person) {'name': '张三', 'age': 30, 'city': '北京'} # 方式2:通过包含双元素的可迭代对象(如列表、元组) >>> pairs = [("name", "李四"), ("age", 25)] >>> person2 = dict(pairs) >>> print(person2) {'name': '李四', 'age': 25} ``` **字典推导式** 类似列表推导式,可通过循环快速生成字典(适合有规律的键值对): ```python >>> square_dict = {x: x**2 for x in range(1, 6)} >>> print(square_dict) {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} ``` 完整版: ```python square_dict = {} # 循环遍历1到5的整数(range(1,6)生成1,2,3,4,5) for x in range(1, 6): square_dict[x] = x **2 print(square_dict) ``` ## 特性 ### 键的唯一性 字典中**键必须是唯一的**,如果出现重复的键,后面的键值对会覆盖前面的(不会报错,但会丢失数据)。 ```python >>> person = {"name": "张三", "age": 30, "name": "李四"} >>> print(person) {'name': '李四', 'age': 30} ``` ### 键的不可变性 字典的**键必须是不可变类型**(即创建后不能修改的数据类型),常见的合法键类型: - 基本类型:整数(int)、浮点数(float)、字符串(str)、布尔值(bool); - 不可变容器:元组(tuple,前提是元组内元素也是不可变的)。 **不合法的键**(可变类型):列表(list)、字典(dict)、集合(set)等(使用会直接报错)。 ```python >>> valid_dict = {("a", "b"): "value"} >>> invalid_dict = {[1, 2]: "value"} Traceback (most recent call last): File "<python-input-15>", line 1, in <module> invalid_dict = {[1, 2]: "value"} ^^^^^^^^^^^^^^^^^ TypeError: unhashable type: 'list' ``` ### 值的任意性 字典的值可以是**任何类型**(包括可变类型),如整数、字符串、列表、字典等,没有限制。 ```python >>> complex_dict = { ... "name": "Python", ... "version": 3.12, ... "features": ["简单", "灵活", "强大"], # 列表作为值 ... "details": {"author": "Guido", "year": 1991} # 字典作为值(嵌套字典) ... } ... >>> print(complex_dict) {'name': 'Python', 'version': 3.12, 'features': ['简单', '灵活', '强大'], 'details': {'author': 'Guido', 'year': 1991}} ``` ### 可变性 字典是**可变的**:可以随时添加新的键值对、修改已有键的值、删除键值对(原字典会被直接修改)。 ## 访问 通过字典名[键]的方式访问对应的值,类似列表通过索引访问元素,但字典用 “键” 而非 “索引”。 ```python >>> person = {"name": "张三", "age": 30, "city": "北京"} >>> print(person["name"]) 张三 >>> print(person["city"]) 北京 ``` 如果访问的键不存在,会直接报错。 ```python >>> print(person["country"]) Traceback (most recent call last): File "<python-input-22>", line 1, in <module> print(person["country"]) ~~~~~~^^^^^^^^^^^ KeyError: 'country' ``` 为了避免这种错误,可以使用get()方法。 ```python >>> print(person.get("country")) None >>> print(person.get("country","不存在")) 不存在 >>> print(person.get("age","不存在")) 30 ``` get()方法的第一个参数用于指定键,第二个参数是当指定的键不存在时要返回的值。 值得注意的是:在调用get()方法时,如果没有指定第二个参数且指定的键不存在时,Python将返回None值,None只是一个表示所需值不存在的特殊值。 ## 修改 通过字典名[键] = 新值的方式,直接修改已有键对应的值(键必须存在)。 ```python >>> person = {"name": "张三", "age": 30} >>> person["age"] = 18 >>> print(person) {'name': '张三', 'age': 18} ``` ## 添加 通过字典名[新键] = 新值的方式,直接添加新的键值对(新键在字典中不存在)。 ```python >>> person = {"name": "张三", "age": 30} >>> person["city"] = "北京" >>> print(person) {'name': '张三', 'age': 30, 'city': '北京'} ``` ## 删除 删除字典中的键值对有多种方式,核心是 “通过键删除”。 对于字典中不再需要的信息,可使用del语句将对于的键值对彻底删除。 ```python >>> print(person) {'name': '张三', 'age': 30, 'city': '北京'} >>> del person['age'] >>> print(person) {'name': '张三', 'city': '北京'} ``` 字典.pop(键),删除指定键的键值对,并**返回对应的值**(键不存在可指定默认值)。 ```python >>> print(person) {'name': '张三', 'city': '北京'} >>> age = person.pop('city') >>> print(age) 北京 >>> print(person) {'name': '张三'} ``` 字典.popitem(),删除**最后插入**的键值对,并返回该键值对(元组形式)。 ```python >>> print(person) {'name': '张三'} >>> person["city"] = "北京" >>> person["age"] = 22 >>> print(person) {'name': '张三', 'city': '北京', 'age': 22} >>> item = person.popitem() >>> print(item) ('age', 22) >>> print(person) {'name': '张三', 'city': '北京'} ``` 字典.clear(),清空字典(删除所有键值对,保留空字典)。 ```py >>> print(person) {'name': '张三', 'city': '北京'} >>> person.clear() >>> print(person) {} ``` ## 复制 复制字典可以使用copy()方法。 ```python >>> username = { ... "username": "Tom", ... "password": "tom123456", ... "age": "20", ... "city": "北京" ... } >>> print(username) {'username': 'Tom', 'password': 'tom123456', 'age': '20', 'city': '北京'} >>> user = username.copy() >>> print(user) {'username': 'Tom', 'password': 'tom123456', 'age': '20', 'city': '北京'} >>> print(username) {'username': 'Tom', 'password': 'tom123456', 'age': '20', 'city': '北京'} >>> user["age"] = 40 >>> print(user) {'username': 'Tom', 'password': 'tom123456', 'age': 40, 'city': '北京'} >>> print(username) {'username': 'Tom', 'password': 'tom123456', 'age': '20', 'city': '北京'} >>> ``` ## 更新 用 “其他字典” 的键值对更新当前字典(存在的键被覆盖,不存在的键被添加),可以使用update()方法。 ```python >>> print(user) {'username': 'Tom', 'password': 'tom123456', 'age': 40, 'city': '北京'} >>> print(username) {'username': 'Tom', 'password': 'tom123456', 'age': '20', 'city': '北京'} >>> username.update(user) >>> print(username) {'username': 'Tom', 'password': 'tom123456', 'age': 40, 'city': '北京'} ``` ## 遍历所有的键值对 现在有这样一个字典: ```python username = { "username": "Tom", "password": "tom123456", "age": "20", "city": "北京" } ``` 对这个字典进行遍历。 ```python >>> for key,value in username.items(): ... print(f"Key:{key}\t") ... print(f"Value:{value}\n") ... Key:username Value:Tom Key:password Value:tom123456 Key:age Value:20 Key:city Value:北京 ``` items()方法返回一个键值对列表,使用for循环依次对每个键值对进行key和value的赋值。 ```python >>> print(username.items()) dict_items([('username', 'Tom'), ('password', 'tom123456'), ('age', '20'), ('city', '北京')]) >>> print(type(username.items())) <class 'dict_items'> ``` ## 遍历字典中所有键 当只需要字典中键时,可以使用keys()方法。 ```python >>> username = { ... "username": "Tom", ... "password": "tom123456", ... "age": "20", ... "city": "北京" ... } >>> >>> for key in username.keys(): ... print(f"Key is {key}") ... Key is username Key is password Key is age Key is city ``` ## 遍历字典中所有值 当只需要字典中值时,可以使用values()方法。 ```python >>> username = { ... "username": "Tom", ... "password": "tom123456", ... "age": "20", ... "city": "北京" ... } >>> >>> for value in username.values(): ... print(f"Value is {value}") ... Value is Tom Value is tom123456 Value is 20 Value is 北京 ``` ## 字典常用方法总结 字典提供了多个内置方法,用于高效操作键值对,常用方法如下: | 方法名 | 功能描述 | 示例 | | ------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | | keys() | 返回字典中所有键的 “视图对象”(可遍历) | person.keys() → dict_keys(['name', 'age']) | | values() | 返回字典中所有值的 “视图对象”(可遍历) | person.values() → dict_values ([' 张三 ', 30]) | | items() | 返回字典中所有键值对的 “视图对象”(每个元素是(键, 值)元组,可遍历) | person.items() → dict_items ([('name', ' 张三 '), ('age', 30)]) | | get(key, default) | 返回键key对应的值,键不存在则返回default(默认None) | person.get("gender", "未知") → "未知" | | setdefault(key, default) | 若键key存在,返回对应值;若不存在,添加key: default并返回default | person.setdefault("gender", "男") → 添加键值对并返回 "男" | | update(其他字典) | 用 “其他字典” 的键值对更新当前字典(存在的键被覆盖,不存在的键被添加) | person.update({"age": 31, "city": "北京"}) | | copy() | 复制字典,返回一个新字典(避免修改原字典) | person2 = person.copy() | ```python >>> username.setdefault("country","中国") '中国' >>> print(username) {'username': 'Tom', 'password': 'tom123456', 'age': 40, 'city': '北京', 'country': '中国'} ``` ## 嵌套字典 字典的值可以是另一个字典(称为 “嵌套字典”),用于表示更复杂的结构化数据(如多个用户信息、多级分类等)。 例如:存储多个用户的信息。 ```python users = { "user1": { "name": "张三", "age": 30, "city": "北京" }, "user2": { "name": "李四", "age": 25, "city": "上海" } } ``` **访问嵌套字典的值** 通过 “多层键” 访问,语法:外层字典[外层键][内层键] ```python >>> users = { ... "user1": { ... "name": "张三", ... "age": 30, ... "city": "北京" ... }, ... "user2": { ... "name": "李四", ... "age": 25, ... "city": "上海" ... } ... } >>> >>> print(users["user1"]["age"]) 30 ``` **遍历嵌套字典** ```python >>> for username, user_info in users.items(): ... print(f"用户名:{username}") ... for key,value in user_info.items(): ... print(f"{key}: {value}") ... 用户名:user1 name: 张三 age: 30 city: 北京 用户名:user2 name: 李四 age: 25 city: 上海 >>> ``` ## 总结 字典是 Python 中处理 “键值关联数据” 的核心类型,核心要点: - 由键值对组成,用{key: value}表示,键唯一且不可变,值可任意类型; - 支持增删改查操作,通过键快速访问值,效率极高; - 适合存储配置信息、用户数据、映射关系等关联数据。
毛林
2025年9月7日 11:45
转发文档
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
Markdown文件
PDF文档(打印)
分享
链接
类型
密码
更新密码