字典
3.1 字典的定义
我们还是先来看看几个例子,看什么叫做字典

输出结果: 确实都是字典



3.2 字典常用操作
1、增加元素:

输出结果:
{'name': 'frog', 'age': 18} {'name': 'frog', 'age': 18, 'weight': 130}
2、删除元素:
a、del 字典[键]

输出结果:
{'name': 'frog', 'age': 18} {'age': 18}
b、字典.pop(键)

输出结果:
{'name': 'frog', 'age': 18} {'name': 'frog'}
注意:pop 删除成功了会返回被删除的值
c、字典.clear

输出结果: {'name': 'frog', 'age': 18} {}
3、修改元素:
a、字典[键] = 数据

输出结果:
{'name': 'frog', 'age': 18, 'weight': 100} {'name': 'frog', 'age': 18, 'weight': 130}
b、字典.setdefault(键,数据)

输出结果:
{'name': 'frog', 'age': 18, 'weight': 100} {'name': 'frog', 'age': 18, 'weight': 100, 'name1': 20}
c、字典.update(字典2)

输出结果:
{'name': 'frog', 'age': 18, 'weight': 100} {'name': 'frog', 'age': 18, 'weight': 80, 'height': 180}
4、查询元素:
1、字典[键]:注意不能根据值来查询键

输出结果: frog
2、字典.get(键)

输出结果:
frog None 没有name键
3、字典的遍历:字典.keys()、字典.values()、字典.items()

输出结果:
dict_keys(['name', 'age', 'weight']) dict_values(['frog', 18, 100]) dict_items([('name', 'frog'), ('age', 18), ('weight', 100)])

输出结果:
name age weight
frog 18 100
name frog age 18 weight 100
注意:如果直接对一个字典进行 for 遍历,取出来的是 键
字典操作总结:

3.3 循环遍历
遍历 就是 依次 从 字典 中获取所有键值对

提示:在实际开发中,由于字典中每一个键值对保存数据的类型是不同的,所以针对字典的循环遍历需求并不是很多
3.4 应用场景

网友评论