4-4.Python 数据容器 - 字典 dict(字典 dict 概述、字典的定义与调用、字典的遍历、字典的常用方法)
·
字典 dict 概述
-
字典用于存储一系列 key-value 键值对
-
字典存储的 key-value 键值对不支持索引
-
字典存储的 key 不可以重复,如果重复,后来存储的 key 对应的 value 会覆盖先前存储的 key 对应的 value
-
字典存储的 key-value 键值对可以是不同类型的,例如、数字、字符串、甚至是其他字典
-
字典是可变的,在程序运行时可以添加、删除、修改其中的 key-value 键值对
一、字典的定义与调用
1、基本介绍
- 字典的定义
【变量】 = {【key 1】: 【value 1】, 【key 2】: 【value 2】, 【key 3】: 【value 3】...}
- 字典的调用
【字典】【key】
2、演示
- 字典的定义
my_dist = {1: "jack", 2: "smith", 3: "tom"}
print(my_dist)
print(type(my_dist))
- 字典的调用
my_dist = {1: "jack", 2: "smith", 3: "tom"}
print(my_dist[1])
print(my_dist[2])
二、字典的遍历
1、for 循环(从 key 开始遍历)
my_dist = {1: "jack", 2: "smith", 3: "tom"}
for key in my_dist.keys():
print(key, my_dist[key])
# 输出结果
1 jack
2 smith
3 tom
2、for 循环(从 value 开始遍历)
my_dist = {1: "jack", 2: "smith", 3: "tom"}
for value in my_dist.values():
print(value)
# 输出结果
jack
smith
tom
三、字典的常用方法
1、基本介绍
| 编号 | 方法 | 说明 |
|---|---|---|
| 1 | 【字典】.pop(【key】) |
删除并获取指定 key 对应的 value |
| 2 | 【字典】.clear() |
清空 key-value 键值对 |
| 3 | 【字典】.keys() |
获取全部的 key |
| 4 | 【字典】.values() |
获取全部的 value |
| 5 | len(【字典】) |
获取字典中的 key-value 键值对数量 |
2、演示
- pop 方法
stu_score = {
"jack": 50,
"tom": 60,
"smith": 70,
}
print(stu_score.pop("jack"))
print(stu_score)
# 输出结果
50
{'tom': 60, 'smith': 70}
- clear 方法
stu_score = {
"jack": 50,
"tom": 60,
"smith": 70,
}
stu_score.clear()
print(stu_score)
# 输出结果
{}
- keys 方法
stu_score = {
"jack": 50,
"tom": 60,
"smith": 70,
}
keys = stu_score.keys()
print(keys)
print(type(keys))
# 输出结果
dict_keys(['jack', 'tom', 'smith'])
<class 'dict_keys'>
- values 方法
stu_score = {
"jack": 50,
"tom": 60,
"smith": 70,
}
values = stu_score.values()
print(values)
print(type(values))
# 输出结果
dict_values([50, 60, 70])
<class 'dict_values'>
- len 方法
stu_score = {
"jack": 50,
"tom": 60,
"smith": 70,
}
print(len(stu_score))
# 输出结果
3
更多推荐



所有评论(0)